PHP variable fun

A little thing I learned the other day about PHP which may  be useful and is definitely fun:

In PHP a variable identifier can be a combination of any letter, number, and certain ASCII characters (that's actually not quite true, but that's irrelevent). The way PHP identifies a variable is by having a $ in front of it. $thisISaVariable is a PHP var, where as thisISaVariable is not. Remember that PHP is a weakly-typed language, so you don't need a type decleration. Any of these statements are valid:
$myvar=5;  //creates an int var
$myvar=6.7;  //creates a float var
$myvar = "Thisis";  //creates a string var.

Where this gets interesting is in the fact that PHP does it’s variable substitution on the fly. Consider this:

$myvar= "ThisIs";
$$myvar="Fun";
echo $myvar ${$myvar}

ThisIsFun

In the first line PHP sets $myvar to “ThisIs”. It then gets tot he second line where it finds a $ sign. Everything after the sign is the variable name, which is stored in a different variable called myvar. PHP dereferences $myvar to find “ThisIS” so it sets $ThisIs=Fun. And thus we get the output above.

How is this useful? Because it allows you to input something into a variable without knowing the variable name at compile time. You’d notice that in the example above, although a variable with the name $ThisIs was created by the program, it’s name was never explicitly used. We could have easily had different input put into $myvar and created any number of differently named variables, without having to change the script one bit. Neat.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: