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. 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:
$a = 1; /* global scope */ Function Test () { echo $a; /* reference to local scope variable */ } Test ();
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. An example:
$a = 1; $b = 2; Function Sum () { global $a, $b; $b = $a + $b; } Sum (); echo $b;
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:
$a = 1; $b = 2; Function Sum () { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum (); echo $b;
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.
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:
Function Test () { $a = 0; echo $a; $a++; }
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:
Function Test () { static $a = 0; echo $a; $a++; }
Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables are also essential when functions are called recursively. 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:
Function Test () { static $count = 0; $count++; echo $count; if ($count < 10) { Test (); } $count--; }
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 = "hello";
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. ie.
$$a = "world";
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:
echo "$a ${$a}";
produces the exact same output as:
echo "$a $hello";
ie. 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.
When a form is submitted to a PHP script, any variables from that form will be automatically made available to the script by PHP. For instance, consider the following form:
Example 5-2. Simple form variable <form action="foo.php3" method="post"> Name: <input type="text" name="name"><br> <input type="submit"> </form> |
When submitted, PHP will create the variable $name, which will will contain whatever what entered into the Name: field on the form.
PHP also understands arrays in the context of form variables, but only in one dimension. You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input:
Example 5-3. More complex form variables <form action="array.html" 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 value="guinness">Guinness </select> <input type="submit"> </form> |
If PHP's track_vars feature is turned on, either by the track_vars configuration setting or the <?php_track_vars?> directive, then variables submitted via the POST or GET methods will also be found in the global associative arrays $HTTP_POST_VARS and $HTTP_GET_VARS as appropriate.
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<input type=image src="image.gif" name="sub">
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.
PHP transparently supports HTTP cookies as defined by Netscape's Spec. 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. Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data.
If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For example:
SetCookie ("MyCookie[]", "Testing", time()+3600);
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.
Example 5-4. SetCookie Example $Count++; SetCookie ("Count", $Count, time()+3600); SetCookie ("Cart[$Count]", $item, time()+3600); |
PHP automatically makes environment variables available as normal PHP variables.
echo $HOME; /* Shows the HOME environment variable, if set. */
Since information coming in via GET, POST and Cookie mechanisms also automatically create PHP variables, it is sometimes best to explicitly read a variable from the environment in order to make sure that you are getting the right version. The getenv() function can be used for this. You can also set an environment variable with the putenv() function.
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a double, then all operands are evaluated as doubles, and the result will be a double. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
$foo = "0"; // $foo is string (ASCII 48) $foo++; // $foo is the string "1" (ASCII 49) $foo += 1; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a double (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15)
If the last two examples above seem odd, see String conversion.
If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype().
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. They are gettype(), is_long(), is_double(), is_string(), is_array(), and is_object().
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
$foo = 10; // $foo is an integer $bar = (double) $foo; // $bar is a double
The casts allowed are:
(int), (integer) - cast to integer
(real), (double), (float) - cast to double
(string) - cast to string
(array) - cast to array
(object) - cast to object
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
$foo = (int) $bar; $foo = ( int ) $bar;
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a double if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
$foo = 1 + "10.5"; // $foo is double (11.5) $foo = 1 + "-1.3e3"; // $foo is double (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 1 + "10 Little Piggies"; // $foo is integer (11); $foo = "10.0 pigs " + 1; // $foo is int (11) $foo = "10.0 pigs " + 1.0; // $foo is double (11)
The type of the variable depends on the second not on the first expression, when the first expression is a string.
For more information on this conversion, see the Unix manual page for strtod(3).