PHP Variable variables


PHP Variable variables

In PHP, it is conceivable to set variable names dynamically. Such a variable uses the value of an existing variable as the name. A variable variable is characterized with two $ signs as the prefix. Sometimes it is convenient to be able to have variable variable names. 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, hello can be used as the name of a variable by using two-dollar signs. i.e.

<?php

$$a = 'Dear';

?>

 

 

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "Dear". Therefore, this statement:

<?php

echo "$a ${$a

}";

?>

 

The above example produces the exact same output as:

<?php

echo "$a $hello";

?>

 

 

Both outputs are: Hello Dear.

In arranging to utilize variable variables with arrays, you've got to resolve an uncertainty problem. That's if you write $$a[1] at that point the parser should know if you implied to use $a[1] as a variable, or if you wanted $$a as the variable, and after that the [1] index from that variable. The syntax for settling this uncertainty is ${$a[1]} for the primary case and ${$a}[1] for the second.

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 you have an expression such as $hello ->$world, then the local scope will be examined for $world and its value will be used as the name of the property of $hello. This is also true if $world is an array access.

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.

Caution: Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

 


Leave a comment
No Cmomments yet