VariablesBasics
Variables in PHP are represented by a dollar sign followed by the
name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A
valid variable name starts with a letter or underscore, followed
by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thus:
^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$
For our purposes here, a letter is a-z, A-Z, and the bytes
from 128 through 255 (0x80-0xff).
$this is a special variable that can't be
assigned.
Prior to PHP 7.1.0, indirect assignment (e.g. by using
variable variables)
was possible.
&tip.userlandnaming;
For information on variable related functions, see the
Variable Functions Reference.
]]>
By default, variables are always assigned by value. That is to say,
when you assign an expression to a variable, the entire value of
the original expression is copied into the destination
variable. This means, for instance, that after assigning one
variable's value to another, changing one of those variables will
have no effect on the other. For more information on this kind of
assignment, see the chapter on Expressions.
PHP also offers another way to assign values to variables:
assign by reference.
This means that the new variable simply references (in other words,
"becomes an alias for" or "points to") the original variable.
Changes to the new variable affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the
beginning of the variable which is being assigned (the source
variable). For instance, the following code snippet outputs 'My
name is Bob' twice:
]]>
One important thing to note is that only named variables may be
assigned by reference.
]]>
It is not necessary to initialize variables in PHP however it is a very
good practice. Uninitialized variables have a default value of their type depending on the context in which they are used
- booleans default to &false;, integers and floats default to zero, strings (e.g. used in echo) are
set as an empty string and arrays become to an empty array.
Default values of uninitialized variables
25
var_dump($unset_int);
// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);
// Array usage; outputs array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);
// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>
]]>
Relying on the default value of an uninitialized variable is problematic
in the case of including one file into another which uses the same
variable name.
E_NOTICE level error is issued in case of
working with uninitialized variables, however not in the case of appending
elements to the uninitialized array. isset language
construct can be used to detect if a variable has been already initialized.
Predefined Variables
PHP provides a large number of predefined variables to any script
which it runs. Many of these variables, however, cannot be fully
documented as they are dependent upon which server is running, the
version and setup of the server, and other factors. Some of these
variables will not be available when PHP is run on the
command line.
Refer to the list of predefined variables
for details.
PHP also provides an additional set of predefined arrays
containing variables from the web server (if applicable), the
environment, and user input. These arrays are rather special
in that they are automatically global - i.e., automatically
available in every scope. For this reason, they are often known as
"superglobals". (There is no mechanism in PHP for
user-defined superglobals.) Refer to the
list of superglobals
for details.
Variable variables
Superglobals cannot be used as
variable variables
inside functions or class methods.
If certain variables in variables_order are not set, their
appropriate PHP predefined arrays are also left empty.
Variable scope
The scope of a variable is the context within which it is defined.
For the most part all PHP variables only have a single scope.
This single scope spans included and required files as well. For
example:
]]>
Here the $a variable will be available within
the included b.inc script. However, within
user-defined functions a local function scope is introduced. Any
variable used inside a function is by default limited to the local
function scope. For example:
]]>
This script will not produce any output because the echo statement
refers to a local version of the $a variable,
and it has not been assigned a value within this scope. You may
notice that this is a little bit different from the C language in
that global variables in C are automatically available to
functions unless specifically overridden by a local definition.
This can cause some problems in that people may inadvertently
change a global variable. In PHP global variables must be
declared global inside a function if they are going to be used in
that function.
The global keyword
First, an example use of global:
Using global
]]>
The above script will output 3. By declaring
$a and $b global within the
function, all references to either variable will refer to the
global version. There is no limit to the number of global
variables that can be manipulated by a function.
A second way to access variables from the global scope is to use
the special PHP-defined $GLOBALS array. The
previous example can be rewritten as:
Using $GLOBALS instead of global
]]>
The $GLOBALS array is an associative array with
the name of the global variable being the key and the contents of
that variable being the value of the array element.
Notice how $GLOBALS exists in any scope, this
is because $GLOBALS is a superglobal.
Here's an example demonstrating the power of superglobals:
Example demonstrating superglobals and scope
]]>
Using global keyword outside a function is not an
error. It can be used if the file is included from inside a function.
Using static variables
Another important feature of variable scoping is the
static variable. A static variable exists
only in a local function scope, but it does not lose its value
when program execution leaves this scope. Consider the following
example:
Example demonstrating need for static variables
]]>
This function is quite useless since every time it is called it
sets $a to 0 and prints
0. The $a++ which increments the
variable serves no purpose since as soon as the function exits the
$a variable disappears. To make a useful
counting function which will not lose track of the current count,
the $a variable is declared static:
Example use of static variables
]]>
Now, $a is initialized only in first call of function
and every time the test() function is called it will print the
value of $a and increment it.
Static variables also provide one way to deal with recursive
functions. A recursive function is one which calls itself. Care
must be taken when writing a recursive function because it is
possible to make it recurse indefinitely. You must make sure you
have an adequate way of terminating the recursion. The following
simple function recursively counts to 10, using the static
variable $count to know when to stop:
Static variables with recursive functions
]]>
Static variables can be assigned values which are the
result of constant expressions, but dynamic expressions, such as function
calls, will cause a parse error.
Declaring static variables
]]>
Static declarations are resolved in compile-time.
References with global and static variables
PHP implements the
static and
global modifier
for variables in terms of
references. For example, a true global variable
imported inside a function scope with the global
statement actually creates a reference to the global variable. This can
lead to unexpected behaviour which the following example addresses:
]]>
&example.outputs;
A similar behaviour applies to the static statement.
References are not stored statically:
property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdclass;
// Assign the object to the static variable
$obj = $new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>
]]>
&example.outputs;
int(1)
}
]]>
This example demonstrates that when assigning a reference to a static
variable, it's not remembered when you call the
&get_instance_ref() function a second time.
Variable variables
Sometimes it is convenient to be able to have variable variable
names. That is, a variable name which can be set and used
dynamically. A normal variable is set with a statement such as:
]]>
A variable variable takes the value of a variable and treats that
as the name of a variable. In the above example,
hello, can be used as the name of a variable
by using two dollar signs. i.e.
]]>
At this point two variables have been defined and stored in the
PHP symbol tree: $a with contents "hello" and
$hello with contents "world". Therefore, this
statement:
]]>
produces the exact same output as:
]]>
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to
resolve an ambiguity problem. That is, if you write
$$a[1] then the parser needs to know if you
meant to use $a[1] as a variable, or if you
wanted $$a as the variable and then the [1]
index from that variable. The syntax for resolving this ambiguity
is: ${$a[1]} for the first case and
${$a}[1] for the second.
Class properties may also be accessed using variable property names. The
variable property name will be resolved within the scope from which the
call is made. For instance, if you have an expression such as
$foo->$bar, then the local scope will be examined for
$bar and its value will be used as the name of the
property of $foo. This is also true if
$bar is an array access.
Curly braces may also be used, to clearly delimit the property
name. They are most useful when accessing values within a property that
contains an array, when the property name is made of multiple parts,
or when the property name contains characters that are not
otherwise valid (e.g. from json_decode
or SimpleXML).
Variable property example
$bar . "\n";
echo $foo->{$baz[1]} . "\n";
$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "\n";
$arr = 'arr';
echo $foo->{$arr[1]} . "\n";
?>
]]>
&example.outputs;
I am bar.
I am bar.
I am bar.
I am r.
Please note that variable variables cannot be used with PHP's
Superglobal arrays
within functions or class methods. The variable $this
is also a special variable that cannot be referenced dynamically.
Variables From External SourcesHTML Forms (GET and POST)
When a form is submitted to a PHP script, the information from
that form is automatically made available to the script. There
are few ways to access this information, for example:
A simple HTML form
Name:
Email:
]]>
There are only two ways to access data from your HTML forms.
Currently available methods are listed below:
Accessing data from a simple POST HTML form
]]>
Using a GET form is similar except you'll use the appropriate
GET predefined variable instead. GET also applies to the
QUERY_STRING (the information after the '?' in a URL). So,
for example, http://www.example.com/test.php?id=3
contains GET data which is accessible with $_GET['id'].
See also $_REQUEST.
Dots and spaces in variable names are converted to underscores. For
example <input name="a.b" /> becomes
$_REQUEST["a_b"].
PHP also understands arrays in the context of form variables
(see the related faq). You may,
for example, group related variables together, or use this
feature to retrieve values from a multiple select input. For
example, let's post a form to itself and upon submission display
the data:
More complex form variables
';
echo htmlspecialchars(print_r($_POST, true));
echo '';
}
?>
]]>
If an external variable name begins with a valid array syntax, trailing characters
are silently ignored. For example, <input name="foo[bar]baz">
becomes $_REQUEST['foo']['bar'].
IMAGE SUBMIT variable names
When submitting a form, it is possible to use an image instead
of the standard submit button with a tag like:
]]>
When the user clicks somewhere on the image, the accompanying
form will be transmitted to the server with two additional
variables, sub_x and sub_y.
These contain the coordinates of the
user click within the image. The experienced may note that the
actual variable names sent by the browser contains a period
rather than an underscore, but PHP converts the period to an
underscore automatically.
HTTP Cookies
PHP transparently supports HTTP cookies as defined by RFC 6265. Cookies are a
mechanism for storing data in the remote browser and thus
tracking or identifying return users. You can set cookies using
the setcookie function. Cookies are part of
the HTTP header, so the SetCookie function must be called before
any output is sent to the browser. This is the same restriction
as for the header function. Cookie data
is then available in the appropriate cookie data arrays, such
as $_COOKIE as well as in $_REQUEST.
See the setcookie manual page for more details and
examples.
As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the names
of incoming cookies are no longer url-decoded for security reasons.
If you wish to assign multiple values to a single cookie variable, you
may assign it as an array. For example:
]]>
That will create two separate cookies although MyCookie will now
be a single array in your script. If you want to set just one cookie
with multiple values, consider using serialize or
explode on the value first.
Note that a cookie will replace a previous cookie by the same
name in your browser unless the path or domain is different. So,
for a shopping cart application you may want to keep a counter
and pass this along. i.e.
A setcookie example
]]>
Dots in incoming variable names
Typically, PHP does not alter the names of variables when they
are passed into a script. However, it should be noted that the
dot (period, full stop) is not a valid character in a PHP
variable name. For the reason, look at it:
]]>
Now, what the parser sees is a variable named
$varname, followed by the string concatenation
operator, followed by the barestring (i.e. unquoted string which
doesn't match any known key or reserved words) 'ext'. Obviously,
this doesn't have the intended result.
For this reason, it is important to note that PHP will
automatically replace any dots in incoming variable names with
underscores.
Determining variable types
Because PHP determines the types of variables and converts them
(generally) as needed, it is not always obvious what type a given
variable is at any one time. PHP includes several functions
which find out what type a variable is, such as:
gettype, is_array,
is_float, is_int,
is_object, and
is_string. See also the chapter on
Types.
HTTP being a text protocol, most, if not all, content that comes in
Superglobal arrays,
like $_POST and $_GET will remain
as strings. PHP will not try to convert values to a specific type.
In the example below, $_GET["var1"] will contain the
string "null" and $_GET["var2"], the string "123".
&reftitle.changelog;
&Version;&Description;7.2.34, 7.3.23, 7.4.11
The names of incoming cookies are no longer url-decoded
for security reasons.