PHP.nl

Variable variables

Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>
A variable variable takes the value of a variable and treats that
as the name of a variable. In the above example,
, can be used as the name of a variable
by using two dollar signs. i.e.

hello

<?php
$$a = 'world';
?>
At this point two variables have been defined and stored in the
PHP symbol tree:  with contents "hello" and
 with contents "world". Therefore, this
statement:

$a``$hello

<?php
echo "$a {$$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: .

In order to use variable variables with arrays,
an ambiguity problem has to be resolved. That is, if the parser sees
 then it needs to know if
 was meant to be used as a variable, or if
 was wanted as the variable and then the 
index from that variable. The syntax for resolving this ambiguity
is:  for the first case and
 for the second. 

$$a[1]``$a[1]``$$a``[1]``${$a[1]}``${$a}[1]

Class properties may also be accessed using variable property names. The
variable property name will be resolved within the scope from which the
call is made. For instance, if there is an expression such as
, then the local scope will be examined for
 and its value will be used as the name of the
property of . This is also true if
 is an array access.

$foo-&gt;$bar``$bar``$foo``$bar

Curly braces may also be used to clearly delimit the property
name. They are most useful when accessing values within a property that
contains an array, when the property name is made of multiple parts,
or when the property name contains characters that are not
otherwise valid (e.g. from 
or ).

json_decodeSimpleXML

Voorbeeld: Variable property example

<?php
class Foo {
    public $bar = 'I am bar.';
    public $arr = ['I am A.', 'I am B.', 'I am C.'];
    public $r   = 'I am r.';
}

$foo = new Foo();
$bar = 'bar';
$baz = ['foo', 'bar', 'baz', 'quux'];
echo $foo->$bar . "\n";
echo $foo->{$baz[1]} . "\n";

$start = 'b';
$end   = 'ar';
echo $foo->{$start . $end} . "\n";

$arr = 'arr';
echo $foo->{$arr[1]} . "\n";
echo $foo->{$arr}[1] . "\n";

?>
I am bar.
I am bar.
I am bar.
I am r.
I am B.

Waarschuwing: > Please note that variable variables cannot be used with PHP's

 within functions or class methods. The variable 
 is also a special variable that cannot be referenced dynamically.
Superglobal arrays`$this`

Documentatie