0

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.

srcspider
  • 10,977
  • 5
  • 40
  • 35
  • 1
    question 1) which php version are you using? question 2) whaaaat? – Ben Jan 31 '13 at 10:25
  • 1
    avoid references when possible. They make your life miserable. And returning null is a well known anti-pattern because it forces is_null checks all over your code. A function should return one type only. – Gordon Jan 31 '13 at 10:34
  • @Ben PHP version is whatever is latest stable version. So at this time 5.4.x. – srcspider Jan 31 '13 at 10:43
  • "Only return references when you have a valid technical reason to do so" [ref](http://php.net/manual/en/language.references.return.php) – Ben Jan 31 '13 at 22:13
  • @Ben Do you know the answer to the question or not? – srcspider Feb 01 '13 at 09:24
  • PHP will never GC anything until reference count is >0. – Roman Newaza Feb 01 '13 at 09:29
  • @RomanNewaza I'm guessing you mean "while reference count is greater then 0." That's all I wanted to know, thanks! Can you post it as an answer so I can accept it? – srcspider Feb 01 '13 at 10:08

1 Answers1

2

PHP will never GC anything while reference count is greater than 0.

Roman Newaza
  • 11,405
  • 11
  • 58
  • 89