php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #45354 Referencing variable variables impossible
Submitted: 2008-06-25 12:57 UTC Modified: 2008-11-06 11:57 UTC
Votes:2
Avg. Score:4.5 ± 0.5
Reproduced:2 of 2 (100.0%)
Same Version:2 (100.0%)
Same OS:2 (100.0%)
From: Sjon at react dot com Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: 5.2.6 OS: Linux
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: Sjon at react dot com
New email:
PHP Version: OS:

 

 [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) {
}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-11-05 11:02 UTC] vrana@php.net
$y_{$a} itself is not documented and it's such a weird construction that it is undocumented by purpose.
 [2008-11-05 15:37 UTC] torben@php.net
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);
?>


Torben
 [2008-11-05 16:13 UTC] Sjon at react dot com
Ah, I see now, instead of $x =& $y_{$a}; I should have used $x =& ${'y_'.$a};

Thanks!
 [2008-11-06 11:57 UTC] Sjon at react dot com
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_
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Dec 06 11:00:02 2025 UTC