Variables
Variables in PHP are identifiers prefixed with a dollar sign
($). For example:
$name$Age$_debugging$MAXIMUM_IMPACT
A variable may hold a value of any type. There is no compile-time or runtime type checking on variables. You can replace a variable’s value with another of a different type:
$what="Fred";$what=35;$what=array("Fred",35,"Wilma");
There is no explicit syntax for declaring variables in PHP. The first time the value of a variable is set, the variable is created. In other words, setting a value to a variable also functions as a declaration. For example, this is a valid complete PHP program:
$day=60*60*24;echo"There are{$day}seconds in a day.\n";Thereare86400secondsinaday.
A variable whose value has not been set behaves like the
NULL value:
if($uninitializedVariable===NULL){echo"Yes!";}Yes!
Variable Variables
You can reference the value of a variable whose name is
stored in another variable by prefacing the variable reference with an
additional dollar sign ($). For
example:
$foo="bar";$$foo="baz";
After the second statement executes, the variable $bar has the value "baz".
Variable References
In PHP, references are how you create variable aliases. To
make $black an alias for the variable
$white, use:
$black=&$white;
The old value of $black, if
any, is lost. Instead, $black is now
another name for the value that is stored in $white:
$bigLongVariableName="PHP";$short=&$bigLongVariableName;$bigLongVariableName.=" rocks!";
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access