开发者

PHP types before function arguments, good or bad?

is there any advantage to p开发者_如何学Pythonroviding types for arguments:

public static function DoStuff( string $str ) {
    echo $str;
}

in comparison to not using them?

public static function DoStuff( $str ) {
    echo $str;
}

Could it possibly run faster if I declare my types?


You cannot (with current versions of PHP) specify scalar types, such as string or int. You can only specify a class/interface, or array.

Relevant page of the manual: Type Hinting.


I see at least one great advantage of using type hinting: readability. It's easier to see what kind of parameter a function/method expects.

Some will see this as a drawback that if you don't respect a type hint and pass some not-type-valid parameter, you'll get a catchable fatal error. However,

  • I personally think it forces the developer to respect your interfaces more
  • It allows your code to just work with the received parameters.
  • The generated error is catchable


If your question is about speed:

  • Making the decision of using type hints or not using type hints should not be the result of performances considerations. You should use or not use the feature.
  • Even if there is some performance impact, it should be pretty minimal. I would say there are many parts of your code that you should optimize before considering this.


In conclusion, a personal opinion: I quite often use those type hints, just so:

  • People using my code know what they are expected to pass in (they don't always read the documentation...)
  • If they don't do what is expected, it fails; hard; in a way they immediately notice
  • My code doesn't have to check if the received parameter is of the right type: I know it is, as PHP enforces that for me.


In general, type checks/type hints are a good thing since it provides the compiler/interpreter necessary information to do better error checking. When you don't type hint, your program might silently crash instead of generate an descriptive error.


The advantage is that you'll get an error right away if someone tries to use your function incorrectly (like using one class instead of another OR not using an array when they should).

However, you cannot do this with anything but objects or arrays - so your example with a string won't work.

It will almost definitely run slower as more checks will occur.


Three advantages for me on php:

  1. Code becomes more self-descriptive
  2. Useful when you need strict validations like numeric or non-set value checking.
  3. Restricts variable usage, by showing non-terminal php errors telling you that you are using wrong variable values.

I'm not sure if performance is improved by using types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜