I was wondering if there is any difference when setting default array value to be an empty array or NULL.
For example:
function arrayTest(array $array = array()) {
if(!empty($array)) {
// Do something
}
}
or
function arrayTest(array $array = NULL) {
if(!empty($array)) {
// Do something
}
}
What I noticed is that the first example doesn't allow NULL values to be passed and the second example does, because of type-casting.
Are there any other differences?
Specifying = null
will indeed allow you to pass null
as an argument.
But another difference is that if you don't pass an argument at all, it will default to array()
or null
, which are two very distinct values. You can check for that of course, but you will need to take it into account. empty
will work for both, but a foreach loop over null
won't work that well, and various array functions will also fail.
Until PHP 7.1 you could only pass null to a type hinted argument if you added = null
to the declaration, making null
the default value.
That was not only true for arrays but for objects as well. And as a side effect of specifying this default value, it would also be possible to invoke the function without specifying an argument at all, which is not always desirable.
Since version 7.1, PHP supports type hinting for nullable arguments and return values, so you can now write:
function arrayTest(?array $array) {
}
In this case the parameter is nullable (you can pass null
to this function). But it's still mandatory to specify the argument explicitly; omitting the parameter is an error.
If to you there is no logical difference between an empty array or null, I would choose the first method of defaulting to an empty array. Then at least you'll know that the input is always an array. I think that add clarity to both the implementer of the function and the programmer(s) who use it. But I guess that's just an opinion and not even a strong one.
My main advice would be to not make the argument optional at all. In my experience this will make the usage of such functions unclear, especially as the code grows and more arguments are added.