Why does a PHP array change when an element is bound to a link?

When ref-assigning an element of an array, the contents of the array change:

$arr = array(100, 200); var_dump($arr); /* shows: array(2) { [0]=> int(100) // ← ← ← int(100) [1]=> int(200) } */ $r = &$arr[0]; var_dump($arr); /* shows: array(2) { [0]=> &int(100) // ← ← ← &int(100) [1]=> int(200) } */ 

Live run. (The Zend Engine will work fine, and the HHVM shows "Process terminated with code 153.")

Why is the item changed?

Why do we see &int(100) instead of int(100) ?

It seems totally strange. What is the explanation for this oddity?

+2
arrays reference php php-internals
source share
1 answer

I answered this a while ago, but cannot find the answer right now. I believe it was like this:

References are simply β€œextra” entries in the symbol table for the same value. A symbol table can only have the values ​​that it points to, and not the values ​​in the values. A character table cannot point to an index in an array; it can only point to a value. Therefore, when you want to make a reference to the index of an array, the value in this index is derived from the array, a symbol is created for it, and the slot in the array receives a reference to the value:

 $foo = array('bar'); symbol | value -------+---------------- foo | array(0 => bar) $baz =& $foo[0]; symbol | value -------+---------------- foo | array(0 => $1) baz | $1 $1 | bar <-- pseudo entry for value that can be referenced 

Because it is impossible:

 symbol | value -------+---------------- foo | array(0 => bar) baz | &foo[0] <-- not supported by symbol table 

$1 above is just an arbitrarily chosen β€œpseudo” name; it has nothing to do with the actual PHP syntax or the way the value actually refers inside.

As pointed out in the comments, here is how a symbol table with links is usually used:

 $a = 1; symbol | value -------+---------------- a | 1 $b = 1; symbol | value -------+---------------- a | 1 b | 1 $c =& a; symbol | value -------+---------------- a, c | 1 b | 1 
+7
source share

All Articles