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 name. 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.
PHP uses a symbol table to store the list of variable names and their values. There are two kinds of symbol tables in PHP: the global symbol table, which stores the list of global variables, and the function-local symbol table, which stores the set of variables available inside each function.
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’s
left is $"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 Webmaster in a Nutshell, Third 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.