Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP types before function arguments, good or bad?

Tags:

types

php

is there any advantage to providing 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?

like image 586
tester Avatar asked Jul 19 '11 22:07

tester


People also ask

Does the order of arguments in a function matter?

Yes, it matters. The arguments must be given in the order the function expects them.

Which is the right way to type hint a function PHP?

To add a type hint to a parameter, you place a type in front of it like this: <? php function my_function(type $param1, type param2, ...) { // ... }

What is the difference between parameter and argument in PHP?

Parameters are temporary variable names within functions. The argument can be thought of as the value that is assigned to that temporary variable.

How many arguments can a PHP function have?

PHP native functions According to the manual, PHP functions may accept up to 12 arguments.


1 Answers

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.
like image 139
Pascal MARTIN Avatar answered Oct 14 '22 14:10

Pascal MARTIN