It’s My Story!

Interesting variable assigning in PHP

August 26, 2007 · 1 Comment

We commonly use the double $ sign to use the value of a variable as a variable name. For example

<?php$Jon = ‘Mrs. Merry’;
$name = ‘Jon’;
echo $$name ;
// We can easily use to get the output “Mrs. Merry”;

?>

Now let’s have a fun.

<?php$name = ‘Jams’;
$$name = ‘Jams Smith’;
echo $$name;
echo $Jams;

?>

What will be the out put. Easily we can evaluate it. Both $$name and $Jams will give same out put “Jams Smith”; Now yesterday I was reading the fundamentals of PHP. Lets see another example.

<? php$name = ‘Ja ms’;
$$name = ‘Jams Smith’;
echo $$name;
echo $Ja ms;

?>

Now $Ja ms will generate a parser error. Because $Ja ms doesn’t follow the convention of variable declaration.

But what about $$name. Is it no confusing…..
But reality is $$name will print ‘Jams Smith’.
PHP manage $$name itself. :)

Categories: PHP

1 response so far ↓

Leave a Comment