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.
An array cannot be null. If it's null, then it is not an array: it is null.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With