|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2008-06-25 12:57 UTC] Sjon at react dot com
Description:
------------
It seems to be impossible to create a reference to a variable variable, even though this is not documented anywhere as a known bug or limitation
Reproduce code:
---------------
$y_a=array();
$a='a';
$x =& $y_{$a}; #DOES NOT WORK
# $x =& $y_a; #DOES WORK
$x['c'] = 'd';
var_dump($y_a);
Expected result:
----------------
array(1) {
["c"]=>
string(1) "d"
}
Actual result:
--------------
array(0) {
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Dec 06 11:00:02 2025 UTC |
$y_{$a} itself is not documented and it's such a weird construction that it is undocumented by purpose.In addition to what Jakub said, variable variables can indeed be assigned by reference in PHP. The problem with the given code example is not that PHP can't assign variable variables by reference, but that the example doesn't make any sense. You're trying to concatenate the value in $a to the end of the value in $y_, which has not been given a value. If you define $y_ properly and use correct syntax then the example will work. See the following examples: <?php $foo = 'I am foo'; $bar = 'foo'; $baz =& $$bar; echo "Ref to varvar: $baz\n"; $y_ = 'y_'; $y_a = array(); $a = 'a'; $x =& ${$y_.$a}; $x['c'] = 'd'; var_dump($y_a); ?> TorbenAh, I see now, instead of $x =& $y_{$a}; I should have used $x =& ${'y_'.$a}; Thanks!btw: I was surprised that $y_{$a} didn't throw a parser exception; but then I realized that it is recognized as a string-offset construction where character at position $a is returned from the variable $y_