Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function foo(array $arg = NULL) -- why the array and NULL?

I've seen the following a few times lately:

 function foo(array $arg = NULL) { ... }

My question being why make the default of $arg NULL when it will be just cast into an array? Why not do:

 function foo(array $arg = array()) { ... }

I know it doesn't really make much difference--it's mostly just reading code--but why encourage PHP to be changing data types all the time.

I've seen this a lot in Kohana.

like image 355
Darryl Hein Avatar asked Aug 20 '10 19:08

Darryl Hein


People also ask

Is array null in PHP?

An array cannot be null. If it's null, then it is not an array: it is null.

How check variable is null in PHP?

The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.

What is $params in PHP?

PHP Parameterized functions They are declared inside the brackets, after the function name. A parameter is a value you pass to a function or strategy. It can be a few value put away in a variable, or a literal value you pass on the fly. They are moreover known as arguments.

What is PHP default argument?

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.


2 Answers

The real question is why create an array when you don't need one.

If you use $arg = array(), there will be a specific instruction to create an array, even if it's PHP an instruction still consumes CPU cycles. If you just do $arg = NULL, then nothing will be done.

like image 121
Colin Hebert Avatar answered Sep 29 '22 07:09

Colin Hebert


My guess is that they want an array for a parameter, but a NULL value for the parameter is acceptible (and will be used by default if an array -- or an explicit NULL -- isn't given).

Note that the array specification in the function signature is not about casting, but is a type hint. It says that only arrays are accepted for $arg.

like image 37
Daniel Vandersluis Avatar answered Sep 29 '22 06:09

Daniel Vandersluis