7

This is the test and the response I get. I think this could be problematic and should throw an error or a notice but I cannot understand why is tolerated.

<?php
    $test = array( 0 => 'test', 1=> &$test );
    var_dump( $test );

    // array(2) { [0]=> string(4) "test" [1]=> &array(2) { [0]=> string(4) "test" [1]=> &array(2) { [0]=> string(4) "test" [1]=> *RECURSION* } } }
?>
3
  • I’m rather surprised that you can reference $test in the same expression that defined $test. $test = array('test'); $test[]=&$test; is pretty clear. But yours … Commented Jan 14, 2010 at 15:45
  • This is not a real problem and I was surprised as well. I was just playing with arrays and hit a personal dilema. Commented Jan 14, 2010 at 15:53
  • @Gumbo PHP is weird. You can assign references before the value exists: $x =& $y; $y = 5; for example is valid, with $y having never been defined earlier. Commented Jul 23, 2013 at 23:39

5 Answers 5

5

It is true recursion, and *RECURSION* is not a real error message. It's not problematic, because $test is not actively recurring, and in this case var_dump is smart enough to stop before exhausting memory.

Sign up to request clarification or add additional context in comments.

Comments

1

I would guess that detecting such a loop is non-trivial, and would be immediately apparent at runtime if the behaviour was incorrect.

Comments

1

Why is it problematic? PHP is smart enough to identify that an array is being recursively called.

The same happens if you print_r($GLOBALS), I see no harm in this.

Comments

1

You're setting a reference, that is, a pointer so there is no true recursion, no loop. So no, it shouldn't throw an error.

Comments

0

Actualy the *RECURSION* message is a error message, which ends the script execution. Else it would execute it till the memory limit is reaced.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.