Showing posts with label Variables. Show all posts
Showing posts with label Variables. Show all posts

Sunday, February 17, 2008

Variables variables en PHP

A veces es conveniente tener nombres de variables variables. Dicho de otro modo, son nombres de variables que se pueden establecer y usar dinámicamente. Una variable normal se establece con una sentencia como:

<?php

$a = "hello";

?>

Una variable variable toma el valor de una variable y lo trata como el nombre de una variable. En el ejemplo anterior, hello, se puede usar como el nombre de una variable utilizando dos signos $. p.ej.

<?php

$$a = "world";

?>

En este momento se han definido y almacenado dos variables en el árbol de símbolos de PHP: $a, que contiene "hello", y $hello, que contiene "world". Es más, esta sentencia:

<?php

echo "$a ${$a}";

?>

produce el mismo resultado que:

<?php

echo "$a $hello";

?>

p.ej. ambas producen el resultado: hello world.

Para usar variables variables con matrices, hay que resolver un problema de ambigüedad. Si se escribe $$a[1] el intérprete necesita saber si nos referimos a utilizar $a[1] como una variable, o si se pretendía utilizar $$a como variable y el índice [1] como índice de dicha variable. La sintaxis para resolver esta ambigüedad es: ${$a[1]} para el primer caso y ${$a}[1] para el segundo.

Tener en cuenta que variables variables no pueden usarse con Matrices superglobales. Esto significa que no se pueden hacer cosas como ${$_GET}.

Friday, February 8, 2008

Variables in PHP

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: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

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

<?php

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

?>

In PHP 3, 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.

As of PHP 4, PHP 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:

<?php

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

<?php

$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 - FALSE, zero, empty string or an empty array.

Example: Default values of uninitialized variables

<?php

echo ($unset_bool ? "true" : "false"); // false

$unset_int += 25; // 0 + 25 => 25

echo $unset_string . "abc"; // "" . "abc" => "abc"

$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")

?>

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.