Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ‘[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Note: $this is a special variable that can’t be assigned.

$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.

By default, variables are always assigned by value. That is to say, when you assign an expression 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 Expressions.

PHP also offers another way to assign values to variables: assign by reference. 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.

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 ‘My name is Bob‘ twice:

$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.

One important thing to note is that only named variables may be assigned by reference.

$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.

function test()
return 25;

$bar = &test(); // Invalid.

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used – booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo()) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

// Unset AND unreferenced (no use context) variable; outputs NULL

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;

// Array usage; outputs array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")

// Object usage; creates new stdClass object (see
// Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Symantec 03, una plataforma que asegura la nube Symantec ha ofrecido nuevos detalles sobre 03, un nuevo servicio cloud que proporciona una capa de seguridad entre los usuarios y las plataformas clou...
Configurar el archivo Robots.txt Explicamos el porqué del archivo robots.txt y como se construye dicho archivo. Para comenzar tenemos que comentar lo que son los robots y qué f...
Razones para cambiarse o actualizar a Windows 8 Windows 8 ya está a la vuelta de la esquina. El nuevo sistema operativo de Microsoft ya circula entre los fabricantes y su versión final para el gran ...
¿ Que es jQuery ? jQuery es una biblioteca de JavaScript, creada inicialmente por John Resig, que permite simplificar la manera de interactuar con los documentos HTML, ...
Google Traductor crea su propia lengua Google anunció que introduciría en su traductor un nuevo sistema llamado GNMT (Google Neural Machine Translation), el cual está basado en el modelo de...
Google Drive vendrá tambien para Linux Google afirmó que está trabajando para dar soporte a Google Drive en Linux, plataforma que fue dejada de lado en esta primera entrega, que sólo co...
Domain Appraisal – Determine the value of your domain name Before you decide to sell a domain you must first determine how much that domain is worth. Each domain that you have is unique and different from any ...
Error Control Operators PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that...
Class EAValidator,Validate an e-mail address by checking its domain Class EAValidator,Validate an e-mail address by checking its domain This class can be used to validate an e-mail address by checking its domain. ...
Diferencias entre hosting en Windows y hosting en Linux A la hora de elegir qué tipo de hosting se debe comprar para alojar una aplicación, es muy necesario tener claro cuáles son las exigencias reales de l...
Variables in PHP
Tagged on: