Variables
In PHP, all variable names begin with a dollar sign
($). The $ is followed by an
alphabetic character or an underscore, and optionally followed by a
sequence of alphanumeric characters and underscores. There is no
limit on the length of a variable. Variable names in PHP are
case-sensitive. Here are some examples:
$i $counter $first_name $_TMP
In PHP, unlike in many other languages, you do not have to explicitly declare variables. PHP automatically declares a variable the first time a value is assigned to it. PHP variables are untyped; you can assign a value of any type to a variable.
Dynamic Variables
Sometimes it is useful to set and use variables dynamically. Normally, you assign a variable like this:
$var = "hello";
Now let’s say you want a variable whose name is the value of
the $var variable. You can do that like this:
$$var = "World";
PHP parses $$var by first dereferencing the
innermost variable, meaning that $var becomes
"hello". The expression that is left is then
$"hello", which is just $hello.
In other words, we have just created a new variable named
hello and assigned it the value
"World". You can nest dynamic variables to an
infinite level in PHP, although once you get beyond two levels, it
can be very confusing for someone who is trying to read your code.
There is a special syntax for using dynamic variables inside quoted strings in PHP:
echo "Hello ${$var}";This syntax is also used to help resolve an ambiguity that occurs when variable arrays are used. Something ...
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