Basically in the case of working with large arrays it's convenient to pass null
back if an error occurs since if $array = null
then $array[] = 1
is [ 1 ]
and null
is also usable in a callable context, ie. function (array $array = null)
will accept null
as an acceptable value. Basically null
is convenient since you can easily identify it as an error if you have error handling code, but also easily ignore it if you don't care.
This is fairly straight forward in most cases, however there is a corner case where PHP doesn't really support it all that well and that's when passing back a reference in the context of a function that doesn't necessarily accept a reference but needs to pass null back sometimes, yet pass a reference back other times (most of the time this is not an issue since you're returning a reference to a instance variable but sometimes that's not the case). There's also the case of calling a function with a null
value in a non awkward way.
The reason to pass the reference is obviously to save the trouble of copying the array around (especially when it's very large).
The following "solution"...
\error_reporting(-1);
function & nil()
{
$nil = null;
return $nil;
}
function & pass(array & $variable = null)
{
return $variable;
}
function & check ()
{
return nil();
}
$test = pass(nil());
$test = &pass(nil());
$test1 = &check();
$test1[] = 1;
$test2 = &check();
$test2[] = 2;
\var_dump($test1, $test2);
Works, but...
My question is Does PHP guarantee the local variable won't be garbage collected before all references to it are garbage collected? or is that undefined behavior.