PHP variables
PHP is one of the languages often used to start programming, I will begin by explaining what a variable is. Then, we’ll look at the types of variables in PHP
So, what is a variable?
A variable is actually a reserved space in memory that we use, and its value can change, which is why it is called a variable. Always use mnemonic names (that reflect the purpose) for variables and avoid using names that are too long.
How I declare a variable in PHP?
In PHP, variables are declared with the $ sign in front, followed by a letter (a, b, …, A, B, …) or an underscore (_). $this
is a special variable that cannot be assigned, which we will cover later.
<?php $variable;// una variable con nombre variable sin definir $4a55;//una variable mal declarada no funcionara $_auto;// esta variable si funcionara ?>
As you can see, in PHP, you don’t need to specify the data type for variables.
To assign a value to a variable, you can use the =
sign.
<?php $var = 4;// le estoy asignando un entero $texto="hola mundo";// le estoy asignando un string ?>
Referencing a variable
We can also assign values to variables by reference, which means the new variable refers to the other one and points to the original variable. Changes to this variable will affect the values in the original variable, and changes in the original will affect this one as well. To reference, use &
.
<?php $a= &$b; //a esta referenciando b /*todo cambio en a afectara b*/ ?>
Variables variables in PHP
Variable variables are variables that can themselves change. Yes, it’s a strange explanation, but it’s better to think of it this way.
Ejemplo:
$a ="hola";
$$a;//is variable variable y is equvalent to put $hola.
These variables are really useful in complex cases; most of the time, you won’t need to use them. For a complex example, imagine you receive values from JavaScript via Ajax, and based on that value, you need to use a variable with that name. In such a case, using a variable variable would be necessary.
Cases where you might use variable variables: crawlers, complex charts, and scenarios involving complex Ajax usage.
Reference: php.net
- Anterior: Tipo de Variables en PHP
- Siguiente: Constantes en PHP