mirror of
https://github.com/php/doc-en.git
synced 2026-03-24 07:42:10 +01:00
1201 lines
33 KiB
XML
1201 lines
33 KiB
XML
<?xml version="1.0" encoding="utf-8"?>
|
|
<!-- $Revision$ -->
|
|
<chapter xml:id="language.variables" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
|
|
<title>Variables</title>
|
|
|
|
<sect1 xml:id="language.variables.basics">
|
|
<title>Basics</title>
|
|
|
|
<simpara>
|
|
Variables in PHP are represented by a dollar sign followed by the
|
|
name of the variable. The variable name is case-sensitive.
|
|
</simpara>
|
|
|
|
<para>
|
|
A valid variable name starts with a letter
|
|
(<literal>A-Z</literal>, <literal>a-z</literal>, or the bytes from 128 through 255)
|
|
or underscore, followed
|
|
by any number of letters, numbers, or underscores. As a regular
|
|
expression, it would be expressed thus:
|
|
<code>^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$</code>
|
|
</para>
|
|
|
|
<note>
|
|
<simpara>
|
|
PHP doesn't support Unicode variable names, however, some character
|
|
encodings (such as UTF-8) encode characters in such a way that all bytes
|
|
of a multi-byte character fall within the allowed range, thus making it a
|
|
valid variable name.
|
|
</simpara>
|
|
</note>
|
|
|
|
<note>
|
|
<simpara>
|
|
<literal>$this</literal> is a special variable that can't be
|
|
assigned.
|
|
Prior to PHP 7.1.0, indirect assignment (e.g. by using
|
|
<link linkend="language.variables.variable">variable variables</link>)
|
|
was possible.
|
|
</simpara>
|
|
</note>
|
|
|
|
&tip.userlandnaming;
|
|
|
|
<example>
|
|
<title>Valid variable names</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$var = 'Bob';
|
|
$Var = 'Joe';
|
|
echo "$var, $Var"; // outputs "Bob, Joe"
|
|
|
|
$_4site = 'not yet'; // valid; starts with an underscore
|
|
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<example>
|
|
<title>Invalid variable names</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$4site = 'not yet'; // invalid; starts with a number
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<simpara>
|
|
PHP accepts a sequence of any bytes as a variable name. Variable
|
|
names that do not follow the above-mentioned naming rules can only be
|
|
accessed dynamically at runtime. See
|
|
<link linkend="language.variables.variable">variable variables</link>
|
|
for information on how to access them.
|
|
</simpara>
|
|
|
|
<example>
|
|
<title>Accessing obscure variable names</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
${'invalid-name'} = 'bar';
|
|
$name = 'invalid-name';
|
|
echo ${'invalid-name'}, " ", $$name;
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
bar bar
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
|
|
<para>
|
|
By default, variables are always assigned by value. That is to say,
|
|
when an expression is assigned 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 <link
|
|
linkend="language.expressions">Expressions</link>.
|
|
</para>
|
|
<para>
|
|
PHP also offers another way to assign values to variables:
|
|
<link linkend="language.references">assign by reference</link>.
|
|
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.
|
|
</para>
|
|
<para>
|
|
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 '<literal>My
|
|
name is Bob</literal>' twice:
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$foo = 'Bob'; // Assign the value 'Bob' to $foo
|
|
$bar = &$foo; // Reference $foo via $bar.
|
|
$bar = "My name is $bar"; // Alter $bar...
|
|
echo $bar;
|
|
echo $foo; // $foo is altered too.
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
</para>
|
|
|
|
<para>
|
|
One important thing to note is that only variables may be
|
|
assigned by reference.
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$foo = 25;
|
|
$bar = &$foo; // This is a valid assignment.
|
|
$bar = &(24 * 7); // Invalid; references an unnamed expression.
|
|
|
|
function test()
|
|
{
|
|
return 25;
|
|
}
|
|
|
|
$bar = &test(); // Invalid because test() doesn't return a variable by reference.
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
</para>
|
|
|
|
<para>
|
|
It is not necessary to declare variables in PHP, however, it is a very
|
|
good practice. Accessing an undefined variable will result in an
|
|
<constant>E_WARNING</constant> (prior to PHP 8.0.0, <constant>E_NOTICE</constant>).
|
|
An undefined variable has a default value of &null;.
|
|
The <function>isset</function> language
|
|
construct can be used to detect if a variable has already been initialized.
|
|
</para>
|
|
<para>
|
|
<example>
|
|
<title>Default value of an uninitialized variable</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// Unset AND unreferenced (no use context) variable.
|
|
var_dump($unset_var);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
Warning: Undefined variable $unset_var in ...
|
|
NULL
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
</para>
|
|
|
|
<simpara>
|
|
PHP allows array autovivification (automatic creation of new arrays)
|
|
from an undefined variable.
|
|
Appending an element to an undefined variable will create a new array and
|
|
will not generate a warning.
|
|
</simpara>
|
|
<example>
|
|
<title>Autovivification of an array from an undefined variable</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$unset_array[] = 'value'; // Does not generate a warning.
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<warning>
|
|
<simpara>
|
|
Relying on the default value of an uninitialized variable is problematic
|
|
when including one file in another which uses the same
|
|
variable name.
|
|
</simpara>
|
|
</warning>
|
|
|
|
<simpara>
|
|
A variable can be destroyed by using the <function>unset</function>
|
|
language construct.
|
|
</simpara>
|
|
|
|
<simpara>
|
|
For information on variable-related functions, see the
|
|
<link linkend="ref.var">Variable Functions Reference</link>.
|
|
</simpara>
|
|
</sect1>
|
|
|
|
<sect1 xml:id="language.variables.predefined">
|
|
<title>Predefined Variables</title>
|
|
|
|
<para>
|
|
PHP provides a number of
|
|
<link linkend="reserved.variables">predefined variables</link>.
|
|
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 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
|
|
<link linkend="language.variables.superglobals">list of superglobals</link>
|
|
for details.
|
|
</para>
|
|
|
|
<note>
|
|
<title>Variable variables</title>
|
|
<para>
|
|
Superglobals cannot be used as
|
|
<link linkend="language.variables.variable">variable variables</link>
|
|
inside functions or class methods.
|
|
</para>
|
|
</note>
|
|
|
|
<para>
|
|
If certain variables in <link
|
|
linkend="ini.variables-order">variables_order</link> are not set, their
|
|
appropriate PHP predefined arrays are also left empty.
|
|
</para>
|
|
</sect1>
|
|
|
|
|
|
<sect1 xml:id="language.variables.scope">
|
|
<title>Variable scope</title>
|
|
|
|
<simpara>
|
|
The scope of a variable is the context within which it is defined.
|
|
PHP has a function scope and a global scope.
|
|
Any variable defined outside a function is limited to the global scope.
|
|
When a file is included, the code it contains inherits the variable scope
|
|
of the line on which the include occurs.
|
|
</simpara>
|
|
<example>
|
|
<title>Example of global variable scope</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$a = 1;
|
|
include 'b.inc'; // Variable $a will be available within b.inc
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<simpara>
|
|
Any variable created inside a named function or an
|
|
<link linkend="functions.anonymous">anonymous</link> function
|
|
is limited to the scope of the function body.
|
|
However, <link linkend="functions.arrow">arrow functions</link>
|
|
bind variables from the parent scope to make them available inside the body.
|
|
If a file include occurs inside a function within
|
|
the calling file, the variables contained in the called file will be
|
|
available as if they had been defined inside the calling function.
|
|
</simpara>
|
|
|
|
<example>
|
|
<title>Example of local variable scope</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$a = 1; // global scope
|
|
|
|
function test()
|
|
{
|
|
echo $a; // Variable $a is undefined as it refers to a local version of $a
|
|
}
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<simpara>
|
|
The example above will generate an undefined variable <constant>E_WARNING</constant>
|
|
(or an <constant>E_NOTICE</constant> prior to PHP 8.0.0).
|
|
This is because the echo statement
|
|
refers to a local version of the <varname>$a</varname> variable,
|
|
and it has not been assigned a value within this scope.
|
|
Note 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.
|
|
</simpara>
|
|
|
|
<sect2 xml:id="language.variables.scope.global">
|
|
<title>The <literal>global</literal> keyword</title>
|
|
<simpara>
|
|
The <literal>global</literal> keyword is used to bind a variable
|
|
from a global scope into a local scope. The keyword can be used with
|
|
a list of variables or a single variable. A local variable will be created
|
|
referencing the global variable of the same name. If the global
|
|
variable does not exist, the variable will be created in global scope and
|
|
assigned &null;.
|
|
</simpara>
|
|
<para>
|
|
<example>
|
|
<title>Using <literal>global</literal></title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$a = 1;
|
|
$b = 2;
|
|
|
|
function Sum()
|
|
{
|
|
global $a, $b;
|
|
|
|
$b = $a + $b;
|
|
}
|
|
|
|
Sum();
|
|
echo $b;
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
3
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
</para>
|
|
|
|
<simpara>
|
|
By declaring
|
|
<varname>$a</varname> and <varname>$b</varname> 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.
|
|
</simpara>
|
|
|
|
<simpara>
|
|
A second way to access variables from the global scope is to use
|
|
the special PHP-defined <varname>$GLOBALS</varname> array. The
|
|
previous example can be rewritten as:
|
|
</simpara>
|
|
<para>
|
|
<example>
|
|
<title>Using <varname>$GLOBALS</varname> instead of global</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$a = 1;
|
|
$b = 2;
|
|
|
|
function Sum()
|
|
{
|
|
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
|
|
}
|
|
|
|
Sum();
|
|
echo $b;
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
|
|
<simpara>
|
|
The <varname>$GLOBALS</varname> 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 <varname>$GLOBALS</varname> exists in any scope, this
|
|
is because <varname>$GLOBALS</varname> is a <link
|
|
linkend="language.variables.superglobals">superglobal</link>.
|
|
Here's an example demonstrating the power of superglobals:
|
|
</simpara>
|
|
<para>
|
|
<example>
|
|
<title>Example demonstrating superglobals and scope</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function test_superglobal()
|
|
{
|
|
echo $_POST['name'];
|
|
}
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
<note>
|
|
<simpara>
|
|
Using <literal>global</literal> keyword outside a function is not an
|
|
error. It can be used if the file is included from inside a function.
|
|
</simpara>
|
|
</note>
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.variables.scope.static">
|
|
<title>Using <literal>static</literal> variables</title>
|
|
<simpara>
|
|
Another important feature of variable scoping is the
|
|
<emphasis>static</emphasis> 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:
|
|
</simpara>
|
|
<para>
|
|
<example>
|
|
<title>Example demonstrating need for static variables</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function test()
|
|
{
|
|
$a = 0;
|
|
echo $a;
|
|
$a++;
|
|
}
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
<simpara>
|
|
This function is quite useless since every time it is called it
|
|
sets <varname>$a</varname> to <literal>0</literal> and prints
|
|
<literal>0</literal>. The <varname>$a</varname>++ which increments the
|
|
variable serves no purpose since as soon as the function exits the
|
|
<varname>$a</varname> variable disappears. To make a useful
|
|
counting function which will not lose track of the current count,
|
|
the <varname>$a</varname> variable is declared static:
|
|
</simpara>
|
|
<para>
|
|
<example>
|
|
<title>Example use of static variables</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function test()
|
|
{
|
|
static $a = 0;
|
|
echo $a;
|
|
$a++;
|
|
}
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
<simpara>
|
|
Now, <varname>$a</varname> is initialized only in first call of function
|
|
and every time the <literal>test()</literal> function is called it will print the
|
|
value of <varname>$a</varname> and increment it.
|
|
</simpara>
|
|
|
|
<simpara>
|
|
Static variables also provide one way to deal with recursive
|
|
functions. The following
|
|
simple function recursively counts to 10, using the static
|
|
variable <varname>$count</varname> to know when to stop:
|
|
</simpara>
|
|
<para>
|
|
<example>
|
|
<title>Static variables with recursive functions</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function test()
|
|
{
|
|
static $count = 0;
|
|
|
|
$count++;
|
|
echo $count;
|
|
if ($count < 10) {
|
|
test();
|
|
}
|
|
$count--;
|
|
}
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
|
|
<para>
|
|
Prior to PHP 8.3.0, static variables could only be initialized using
|
|
a constant expression. As of PHP 8.3.0, dynamic expressions
|
|
(e.g. function calls) are also allowed:
|
|
</para>
|
|
<para>
|
|
<example>
|
|
<title>Declaring static variables</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function foo(){
|
|
static $int = 0; // correct
|
|
static $int = 1+2; // correct
|
|
static $int = sqrt(121); // correct as of PHP 8.3.0
|
|
|
|
$int++;
|
|
echo $int;
|
|
}
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
|
|
<simpara>
|
|
Static variables inside anonymous functions persist only within that
|
|
specific function instance. If the anonymous function is recreated on each
|
|
call, the static variable will be reinitialized.
|
|
</simpara>
|
|
<example>
|
|
<title>Static variables in anonymous functions</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function exampleFunction($input) {
|
|
$result = (static function () use ($input) {
|
|
static $counter = 0;
|
|
$counter++;
|
|
return "Input: $input, Counter: $counter\n";
|
|
});
|
|
|
|
return $result();
|
|
}
|
|
|
|
// Calls to exampleFunction will recreate the anonymous function, so the static
|
|
// variable does not retain its value.
|
|
echo exampleFunction('A'); // Outputs: Input: A, Counter: 1
|
|
echo exampleFunction('B'); // Outputs: Input: B, Counter: 1
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<para>
|
|
As of PHP 8.1.0, when a method using static variables is inherited (but not overridden),
|
|
the inherited method will now share static variables with the parent method.
|
|
This means that static variables in methods now behave the same way as static properties.
|
|
</para>
|
|
|
|
<simpara>
|
|
As of PHP 8.3.0, static variables can be initialized with arbitrary expressions.
|
|
This means that method calls, for example, can be used to initialize static variables.
|
|
</simpara>
|
|
|
|
<example>
|
|
<title>Usage of static Variables in Inherited Methods</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
class Foo {
|
|
public static function counter() {
|
|
static $counter = 0;
|
|
$counter++;
|
|
return $counter;
|
|
}
|
|
}
|
|
class Bar extends Foo {}
|
|
var_dump(Foo::counter()); // int(1)
|
|
var_dump(Foo::counter()); // int(2)
|
|
var_dump(Bar::counter()); // int(3), prior to PHP 8.1.0 int(1)
|
|
var_dump(Bar::counter()); // int(4), prior to PHP 8.1.0 int(2)
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.variables.scope.references">
|
|
<title>References with <literal>global</literal> and <literal>static</literal> variables</title>
|
|
<simpara>
|
|
PHP implements the
|
|
<link linkend="language.variables.scope.static">static</link> and
|
|
<link linkend="language.variables.scope.global">global</link> modifier
|
|
for variables in terms of <link linkend="language.references">
|
|
references</link>. For example, a true global variable
|
|
imported inside a function scope with the <literal>global</literal>
|
|
statement actually creates a reference to the global variable. This can
|
|
lead to unexpected behaviour which the following example addresses:
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function test_global_ref() {
|
|
global $obj;
|
|
$new = new stdClass;
|
|
$obj = &$new;
|
|
}
|
|
|
|
function test_global_noref() {
|
|
global $obj;
|
|
$new = new stdClass;
|
|
$obj = $new;
|
|
}
|
|
|
|
test_global_ref();
|
|
var_dump($obj);
|
|
test_global_noref();
|
|
var_dump($obj);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
&example.outputs;
|
|
|
|
<screen>
|
|
<![CDATA[
|
|
NULL
|
|
object(stdClass)#1 (0) {
|
|
}
|
|
]]>
|
|
</screen>
|
|
|
|
<simpara>
|
|
A similar behaviour applies to the <literal>static</literal> statement.
|
|
References are not stored statically:
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function &get_instance_ref() {
|
|
static $obj;
|
|
|
|
echo 'Static object: ';
|
|
var_dump($obj);
|
|
if (!isset($obj)) {
|
|
$new = new stdClass;
|
|
// Assign a reference to the static variable
|
|
$obj = &$new;
|
|
}
|
|
if (!isset($obj->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();
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
Static object: NULL
|
|
Static object: NULL
|
|
|
|
Static object: NULL
|
|
Static object: object(stdClass)#3 (1) {
|
|
["property"]=>
|
|
int(1)
|
|
}
|
|
]]>
|
|
</screen>
|
|
|
|
<simpara>
|
|
This example demonstrates that when assigning a reference to a static
|
|
variable, it is not <emphasis>remembered</emphasis> when the
|
|
<literal>&get_instance_ref()</literal> function is called a second time.
|
|
</simpara>
|
|
</sect2>
|
|
</sect1>
|
|
|
|
<sect1 xml:id="language.variables.variable">
|
|
<title>Variable variables</title>
|
|
|
|
<simpara>
|
|
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:
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$a = 'hello';
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<simpara>
|
|
A variable variable takes the value of a variable and treats that
|
|
as the name of a variable. In the above example,
|
|
<emphasis>hello</emphasis>, can be used as the name of a variable
|
|
by using two dollar signs. i.e.
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$$a = 'world';
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<simpara>
|
|
At this point two variables have been defined and stored in the
|
|
PHP symbol tree: <varname>$a</varname> with contents "hello" and
|
|
<varname>$hello</varname> with contents "world". Therefore, this
|
|
statement:
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
echo "$a {$$a}";
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<simpara>
|
|
produces the exact same output as:
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
echo "$a $hello";
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<simpara>
|
|
i.e. they both produce: <computeroutput>hello world</computeroutput>.
|
|
</simpara>
|
|
|
|
<simpara>
|
|
In order to use variable variables with arrays,
|
|
an ambiguity problem has to be resolved. That is, if the parser sees
|
|
<varname>$$a[1]</varname> then it needs to know if
|
|
<varname>$a[1]</varname> was meant to be used as a variable, or if
|
|
<varname>$$a</varname> was wanted as the variable and then the <literal>[1]</literal>
|
|
index from that variable. The syntax for resolving this ambiguity
|
|
is: <varname>${$a[1]}</varname> for the first case and
|
|
<varname>${$a}[1]</varname> for the second.
|
|
</simpara>
|
|
|
|
<simpara>
|
|
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 there is an expression such as
|
|
<varname>$foo->$bar</varname>, then the local scope will be examined for
|
|
<varname>$bar</varname> and its value will be used as the name of the
|
|
property of <varname>$foo</varname>. This is also true if
|
|
<varname>$bar</varname> is an array access.
|
|
</simpara>
|
|
|
|
<simpara>
|
|
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 <function>json_decode</function>
|
|
or <link linkend="book.simplexml">SimpleXML</link>).
|
|
</simpara>
|
|
|
|
<para>
|
|
<example>
|
|
<title>Variable property example</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
class Foo {
|
|
public $bar = 'I am bar.';
|
|
public $arr = ['I am A.', 'I am B.', 'I am C.'];
|
|
public $r = 'I am r.';
|
|
}
|
|
|
|
$foo = new Foo();
|
|
$bar = 'bar';
|
|
$baz = ['foo', 'bar', 'baz', 'quux'];
|
|
echo $foo->$bar . "\n";
|
|
echo $foo->{$baz[1]} . "\n";
|
|
|
|
$start = 'b';
|
|
$end = 'ar';
|
|
echo $foo->{$start . $end} . "\n";
|
|
|
|
$arr = 'arr';
|
|
echo $foo->{$arr[1]} . "\n";
|
|
echo $foo->{$arr}[1] . "\n";
|
|
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
I am bar.
|
|
I am bar.
|
|
I am bar.
|
|
I am r.
|
|
I am B.
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
</para>
|
|
|
|
<warning>
|
|
<simpara>
|
|
Please note that variable variables cannot be used with PHP's
|
|
<link linkend="language.variables.superglobals">Superglobal arrays</link>
|
|
within functions or class methods. The variable <literal>$this</literal>
|
|
is also a special variable that cannot be referenced dynamically.
|
|
</simpara>
|
|
</warning>
|
|
|
|
</sect1>
|
|
|
|
<sect1 xml:id="language.variables.external">
|
|
<title>Variables From External Sources</title>
|
|
|
|
<sect2 xml:id="language.variables.external.form">
|
|
<title>HTML Forms (GET and POST)</title>
|
|
|
|
<simpara>
|
|
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:
|
|
</simpara>
|
|
|
|
<para>
|
|
<example>
|
|
<title>A simple HTML form</title>
|
|
<programlisting role="html">
|
|
<![CDATA[
|
|
<form action="foo.php" method="post">
|
|
Name: <input type="text" name="username" /><br />
|
|
Email: <input type="text" name="email" /><br />
|
|
<input type="submit" name="submit" value="Submit me!" />
|
|
</form>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
|
|
<para>
|
|
There are only two ways to access data from HTML forms.
|
|
Currently available methods are listed below:
|
|
</para>
|
|
|
|
<para>
|
|
<example>
|
|
<title>Accessing data from a simple POST HTML form</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
echo $_POST['username'];
|
|
echo $_REQUEST['username'];
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
|
|
<para>
|
|
Using a GET form is similar except the appropriate
|
|
GET predefined variable can be used instead. GET also applies to the
|
|
<literal>QUERY_STRING</literal> (the information after the '?' in a URL). So,
|
|
for example, <literal>http://www.example.com/test.php?id=3</literal>
|
|
contains GET data which is accessible with <varname>$_GET['id']</varname>.
|
|
See also <varname>$_REQUEST</varname>.
|
|
</para>
|
|
|
|
<note>
|
|
<para>
|
|
Dots and spaces in variable names are converted to underscores. For
|
|
example <literal><input name="a.b" /></literal> becomes
|
|
<literal>$_REQUEST["a_b"]</literal>.
|
|
</para>
|
|
</note>
|
|
|
|
<simpara>
|
|
PHP also understands arrays in the context of form variables
|
|
(see the <link linkend="faq.html">related faq</link>).
|
|
For example, related variables may be grouped together, or this
|
|
feature may be used to retrieve values from a multiple select input. For
|
|
example, let's post a form to itself and upon submission display
|
|
the data:
|
|
</simpara>
|
|
|
|
<para>
|
|
<example>
|
|
<title>More complex form variables</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
if ($_POST) {
|
|
echo '<pre>';
|
|
echo htmlspecialchars(print_r($_POST, true));
|
|
echo '</pre>';
|
|
}
|
|
?>
|
|
<form action="" method="post">
|
|
Name: <input type="text" name="personal[name]" /><br />
|
|
Email: <input type="text" name="personal[email]" /><br />
|
|
Beer: <br />
|
|
<select multiple name="beer[]">
|
|
<option value="warthog">Warthog</option>
|
|
<option value="guinness">Guinness</option>
|
|
<option value="stuttgarter">Stuttgarter Schwabenbräu</option>
|
|
</select><br />
|
|
<input type="submit" value="submit me!" />
|
|
</form>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
|
|
<note>
|
|
<simpara>
|
|
If an external variable name begins with a valid array syntax, trailing characters
|
|
are silently ignored. For example, <literal><input name="foo[bar]baz"></literal>
|
|
becomes <literal>$_REQUEST['foo']['bar']</literal>.
|
|
</simpara>
|
|
</note>
|
|
|
|
<sect3 xml:id="language.variables.external.form.submit">
|
|
<title>IMAGE SUBMIT variable names</title>
|
|
|
|
<simpara>
|
|
When submitting a form, it is possible to use an image instead
|
|
of the standard submit button with a tag like:
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="html">
|
|
<![CDATA[
|
|
<input type="image" src="image.gif" name="sub" />
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<simpara>
|
|
When the user clicks somewhere on the image, the accompanying
|
|
form will be transmitted to the server with two additional
|
|
variables, <varname>sub_x</varname> and <varname>sub_y</varname>.
|
|
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.
|
|
</simpara>
|
|
</sect3>
|
|
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.variables.external.cookies">
|
|
<title>HTTP Cookies</title>
|
|
|
|
<simpara>
|
|
PHP transparently supports HTTP cookies as defined by <link
|
|
xlink:href="&url.rfc;6265">RFC 6265</link>. Cookies are a
|
|
mechanism for storing data in the remote browser and thus
|
|
tracking or identifying return users. It is possible to set cookies using
|
|
the <function>setcookie</function> 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 <function>header</function> function. Cookie data
|
|
is then available in the appropriate cookie data arrays, such
|
|
as <varname>$_COOKIE</varname> as well as in <varname>$_REQUEST</varname>.
|
|
See the <function>setcookie</function> manual page for more details and
|
|
examples.
|
|
</simpara>
|
|
|
|
<note>
|
|
<simpara>
|
|
As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the <emphasis>names</emphasis>
|
|
of incoming cookies are no longer url-decoded for security reasons.
|
|
</simpara>
|
|
</note>
|
|
|
|
<simpara>
|
|
If multiple values should be assigned to a single cookie variable,
|
|
they can be assigned as an array. For example:
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
|
|
setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<simpara>
|
|
That will create two separate cookies although <varname>MyCookie</varname> will now
|
|
be a single array in the script. If just one cookie should be set
|
|
with multiple values, consider using <function>serialize</function> or
|
|
<function>explode</function> on the value first.
|
|
</simpara>
|
|
|
|
<simpara>
|
|
Note that a cookie will replace a previous cookie by the same
|
|
name in the browser unless the path or domain is different. So,
|
|
for a shopping cart application a counter may be kept,
|
|
and passed along. I.e.
|
|
</simpara>
|
|
|
|
<example>
|
|
<title>A <function>setcookie</function> example</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
if (isset($_COOKIE['count'])) {
|
|
$count = $_COOKIE['count'] + 1;
|
|
} else {
|
|
$count = 1;
|
|
}
|
|
setcookie('count', $count, time()+3600);
|
|
setcookie("Cart[$count]", $item, time()+3600);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.variables.external.dot-in-names">
|
|
<title>Dots in incoming variable names</title>
|
|
|
|
<para>
|
|
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:
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$varname.ext; /* invalid variable name */
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
Now, what the parser sees is a variable named
|
|
<varname>$varname</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.
|
|
</para>
|
|
|
|
<para>
|
|
For this reason, it is important to note that PHP will
|
|
automatically replace any dots in incoming variable names with
|
|
underscores.
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.variables.determining-type-of">
|
|
<title>Determining variable types</title>
|
|
|
|
<para>
|
|
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:
|
|
<function>gettype</function>, <function>is_array</function>,
|
|
<function>is_float</function>, <function>is_int</function>,
|
|
<function>is_object</function>, and
|
|
<function>is_string</function>. See also the chapter on
|
|
<link linkend="language.types">Types</link>.
|
|
</para>
|
|
<para>
|
|
HTTP being a text protocol, most, if not all, content that comes in
|
|
<link linkend="language.variables.superglobals">Superglobal arrays</link>,
|
|
like <varname>$_POST</varname> and <varname>$_GET</varname> will remain
|
|
as strings. PHP will not try to convert values to a specific type.
|
|
In the example below, <varname>$_GET["var1"]</varname> will contain the
|
|
string "null" and <varname>$_GET["var2"]</varname>, the string "123".
|
|
<programlisting>
|
|
<![CDATA[
|
|
/index.php?var1=null&var2=123
|
|
]]>
|
|
</programlisting>
|
|
</para>
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.variables.external.changelog">
|
|
&reftitle.changelog;
|
|
|
|
<para>
|
|
<informaltable>
|
|
<tgroup cols="2">
|
|
<thead>
|
|
<row>
|
|
<entry>&Version;</entry>
|
|
<entry>&Description;</entry>
|
|
</row>
|
|
</thead>
|
|
<tbody>
|
|
<row>
|
|
<entry>7.2.34, 7.3.23, 7.4.11</entry>
|
|
<entry>
|
|
The <emphasis>names</emphasis> of incoming cookies are no longer url-decoded
|
|
for security reasons.
|
|
</entry>
|
|
</row>
|
|
</tbody>
|
|
</tgroup>
|
|
</informaltable>
|
|
</para>
|
|
</sect2>
|
|
|
|
</sect1>
|
|
|
|
</chapter>
|
|
|
|
<!-- Keep this comment at the end of the file
|
|
Local variables:
|
|
mode: sgml
|
|
sgml-omittag:t
|
|
sgml-shorttag:t
|
|
sgml-minimize-attributes:nil
|
|
sgml-always-quote-attributes:t
|
|
sgml-indent-step:1
|
|
sgml-indent-data:t
|
|
indent-tabs-mode:nil
|
|
sgml-parent-document:nil
|
|
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
|
|
sgml-exposed-tags:nil
|
|
sgml-local-catalogs:nil
|
|
sgml-local-ecat-files:nil
|
|
End:
|
|
vim600: syn=xml fen fdm=syntax fdl=2 si
|
|
vim: et tw=78 syn=sgml
|
|
vi: ts=1 sw=1
|
|
-->
|