Monday 22 April 2013

What is variable variables in PHP

Variable Variables are just variables whose name can be set and accessed by programmatically.


How to use variable variables?

Example:


<?php
$myVar = "hello";
?>
            

Now can you imagine, in the above example "hello" can be use as the name of a variable by using two dollor signs. i.e.

<?php
$$myVar = "world!!";
?>
            

Variable Variables takes the value of a variable and treat that as the name of variable. In the example above it is treating "hello" as a variable.

<?php

echo $myVar . "<br>";
//Output: hello

echo $hello . "<br>";
//Output: world!!

echo "$myVar $hello";
//Output: hello world!!

?>
            

If you don't want to use "hello" as a variable name (which is I think not a better way) then you can use double dollor sign ($$). i.e.

<?php

echo $myVar . "<br>";
//Output: hello

echo $$myVar . "<br>";
//Output: world!!

echo "$myVar ${$myVar}" . "<br>";
//Output: hello word!!
?>
            

For more reference visit PHP Manual: http://php.net/manual/en/language.variables.variable.php

Thanks. Have a great day!!

No comments:

Post a Comment