Assigning Values
Variables are assigned values using the assignment operator (=). For all but the array and object types, the assignment is simple:
$boolean = true;
$int = 5;
$float = 56.98;
$string = 'something';
$dbc = mysqli_connect('host', 'user', 'password', 'database');
$null = NULL;
Note that numbers, Booleans, and NULL values are never quoted. Strings are always quoted.
Arrays are variables that can contain multiple elements (key-value pairs). To assign a value to an array element, special array notation is required:
$array[] = 'value';
To assign the value with a specific index, use:
$array[3] = 'value';
$array['key'] = 2354;
Object variables are assigned values using the assignment operator but also require use of the new keyword:
$obj = new SomeClass();
Pre-Defined Variables
PHP has several pre-defined variables, known as the Superglobals. These are used to access data external to the script. See this article for details.
PHP Variable Scope
A variable's scope refers to the realm in which it exists. Every variable defined in a script exists within that script and within any included file. With this code, the included file can also refer to $var:
$var = 60.59;
include ('somefile.php');
Note that, with the exception of some of the Superglobals, every variable in PHP is unset (i.e., deleted) when a script stops executing.
Variables defined within a function have local scope:
function my_func() {
$var = 5; // local
}
That variable only exists inside of the function. Once the function stops executing, the variable ceases to exist. Inside of a function, you cannot refer to a variable defined outside of a function without using the global keyword:
$var = 5;
function my_func() {
global $var;
}
In that code, the $var variable inside of the function is now the same as that outside of the function. Without using the global keyword, two variables with the same name—one inside of a function and one outside of it—are two separate, unrelated variables.
PHP's Superglobals automatically have global scope, and can be accessed inside of a function without using the global keyword.
As an important debugging tool, NuSphere's PhpED lists, and shows the values of, both local and global variables in a script (see the images).
|