Zend PHP 5 – Basics – Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable.

They can contain letters, numbers and underscores, although must not start with a number.

By convention, variables start with lower case and then each word afterwards starts with a capital letter. Note that variables are case sensitive, so the following would print out different values:

$someVariable = "Something";
$SomeVariable = "Something else";

echo $someVariable; // Something
echo $SomeVariable; // Something else

Variables by default are assigned by value, which means that the left operand gets set to the value of the expression on the right. It does not mean “equal to”.

Variables can also be assigned by reference, which means that both variables end up pointing at the same data, and nothing is copied anywhere.

References use the & symbol.

<?php
$foo = 'Some value';         // Assign the value 'Some value' to $foo
$bar = &$foo;                // Reference $foo via $bar.
$bar = "Some other value";   // Alter $bar...
echo $bar;                   // Prints out 'Some other value'
echo $foo;                   // Also prints out 'Some other value'

It is not necessary to initialise variables in PHP however it is a very good practice. PHP will throw an E_NOTICE level error message if an uninitialised variable is used.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo $somevar; // Throws a "Notice: Undefined variable: somevar" message.

The isset() function determines if a variable is set and is not NULL. If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL.

<?php
$var = '';

if (isset($var)) {
    echo "var is set";          // This prints out
} else {
    echo "var is not set";
}

if (isset($otherVar)) {
    echo "otherVar is set";
} else {
    echo "otherVar is not set";  // This prints out
}

PHP provides a list of predefined variables, some of which can be seen below:

  • $GLOBALS — References all variables available in global scope
  • $_SERVER — Server and execution environment information
  • $_GET — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_FILES — HTTP File Upload variables
  • $_REQUEST — HTTP Request variables
  • $_SESSION — Session variables
  • $_ENV — Environment variables
  • $_COOKIE — HTTP Cookies
  • $php_errormsg – The previous error message

Note: This article is based on PHP version 5.5.