Variables in PHP
A variable is a special container that you can define, which will then “hold” avalue, such as a number, string, object, array, or a Boolean. Variables are fundamental to programming. Without variables, we would be forced to hard-code all the values in our scripts.
A variable consists of a name of your choosing, preceded by a dollar sign ($).
Variable names can include letters, numbers, and the underscore character (_),but they cannot include spaces. Names must begin with a letter or an underscore. The following list shows some legal variables:
When you declare a variable, you usually assign a value to it in the same statement, as shown here:
$num1 = 8;
$num2 = 23;
The preceding lines declare two variables, using the assignment operator (=) to give them values. You will learn about assignment in more detail in the“Operators and Expressions” section later in this chapter. After you assign values to your variables, you can treat them exactly as if they were the values themselves. In other words
is equivalent to
as long as $num1 is assigned a value of 8.
Globals and Superglobals
In addition to the rules for naming variables, there are rules regarding the availability of variables. In general, the assigned value of a variable is present only within the function or script where it resides. For example, if you have
scriptA.php which holds a variable called $name with a value of joe, and you want to create scriptB.php that also uses a $name variable, you can assign to it a value of jane without affecting scriptA.php. The value of the $name variable is local to each script, and the assigned values are independent of each other.
However, you can also define the $name variable as global in a script or function. If this is the case in scriptA.php and scriptB.php, and these scripts are connected, there will only be one value for the now-shared $name variable.
In addition to global variables of your own creation, PHP has several predefined variables called superglobals. These variables are always present, and their values available to all of your scripts. Each of the following superglobals is actually an array of other variables:
. $_GET contains any variables provided to a script through the GET method.
. $_POST contains any variables provided to a script through the POST method.
. $_COOKIE contains any variables provided to a script through a cookie.
. $_FILES contains any variables provided to a script through file uploads.
. $_SERVER contains information such as headers, file paths, and script locations.
. $_ENV contains any variables provided to a script as part of the server environment.
. $_REQUEST contains any variables provided to a script via any user input mechanism.
. $_SESSION contains any variables that are currently registered in a session.