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
"
;
There
are
86400
seconds
in
a
day
.
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!"
;
Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.