|
|
 |
CapÃtulo 12. Variables
En PHP las variables se representan como un signo de dólar
seguido por el nombre de la variable. El nombre de la variable es
sensible a minúsculas y mayúsculas.
Los nombres de variables siguen las mismas reglas que otras
etiquetas en PHP. Un nombre de variable valido tiene que empezar
con una letra o una raya (underscore), seguido de cualquier número
de letras, números y rayas. Como expresión regular se podria
expresar como: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Nota:
En nuestro caso, una letra es a-z, A-Z, y los caracteres ASCII del
127 al 255 (0x7f-0xff).
En PHP3, las variables siempre se asignan por valor. Esto significa
que cuando se asigna una expresión a una variable, el valor
Ãntegro de la expresión original se copia en la
variable de destino. Esto quiere decir que, por ejemplo,
después e asignar el valor de una variable a otra, los
cambios que se efectúen a una de esas variables no
afectará a la otra. Para más información sobre
este tipo de asignación, vea Expresiones.
PHP4 ofrece otra forma de asignar valores a las variables:
asignar por referencia. Esto significa que la
nueva variable simplemente referencia (en otras palabras, "se
convierte en un alias de" ó "apunta a") la variable original. Los
cambios a la nueva variable afectan a la original, y
viceversa. Esto también significa que no se produce una
copia de valores; por tanto, la asignación ocurre más
rápidamente. De cualquier forma, cualquier incremento de
velocidad se notará sólo en los bucles
crÃticos cuando se asignen grandes matrices u objetos.
Para asignar por referencia, simplemente se antepone un
ampersandsigno "&" al comienzo de la variable cuyo valor se
está asignando (la variable fuente). Por ejemplo, el
siguiente trozo de código produce la salida 'Mi nombre es
Bob' dos veces:
Algo importante a tener en cuenta es que sólo las variables
con nombre pueden ser asignadas por referencia.
giunta dot gaetano at sea-aeroportimilano dot it
04-Aug-2006 01:44
With php 5.1.4 (and maybe earlier?) take care about not using $this as a variable name, even when in the global scope or inside a plain function: the engine will prevent assigning any value to it...
molnaromatic at gmail dot com
20-May-2006 05:44
Simple sample and variables and html "templates":
The PHP code:
variables.php:
<?php
$SYSN["title"] = "This is Magic!";
$SYSN["HEADLINE"] = "Ez magyarul van"; $SYSN["FEAR"] = "Bell in my heart";
?>
http://indices.com.es/index.html:
<?php
include("variables.php");
include("template.html");
?>
The template:
template.html
<html>
<head><title><?=$SYSN["title"]?></title></head>
<body>
<H1><?=$SYSN["HEADLINE"]?></H1>
<p><?=$SYSN["FEAR"]?></p>
</body>
</html>
This is simple, quick and very flexibile
warhog at warhog dot net
27-Dec-2005 11:11
> 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]*'
..is not quite true. You can, in fact, only declare variables having a name like this if you use the syntax <?php $varname = "naks naks"; ?>.. but in fact a variable can have moreless any name that is a string... e.g. if you look at an array you can have
<?php
$arr[''];
$arr['8'];
$arr['-my-element-is-so-pretty-useless-'];
?>
.. by accessing the variables-namespace via {} you can have the same functinalities for all variables, e.g.
<?php ${''} = "my empty variable"; ?>
is a valid expression and the variable having the empty string as name will have the value "my empty variable".
read the chapter on "variable variables" for further information.
Mike at ImmortalSoFar dot com
25-Nov-2005 02:03
References and "return" can be flakey:
<?php
function &GetLogin ()
{
return $_SESSION['Login'];
}
function &GetLogin ()
{
return &$_SESSION['Login'];
}
function &GetLogin ()
{
$ret = &$_SESSION['Login'];
return $ret;
}
?>
david at removethisbit dot futuresbright dot com
10-Nov-2005 01:25
When using variable variables this is invalid:
$my_variable_{$type}_name = true;
to get around this do something like:
$n="my_variable_{$type}_name";
${$n} = true;
(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...)
ludvig dot ericson at gmail dot com
13-Oct-2005 04:33
On the previous note:
This is due to how evaluation works. PHP will think of it as:
$a = whatever $b = $c is
$b = whatever $c = 1 is
... because an expression is equal to what it returns.
Therefore $c = 1 returns 1, making $b = $c same as $b = 1, which makes $b 1, which makes $a be $b, which is 1.
$a = ($b = $c = 1) + 2;
Will have $a be 3 while $b and $c is 1.
Hope that clears something up.
Chris Hester
31-Aug-2005 05:09
Variables can also be assigned together.
<?php
$a = $b = $c = 1;
echo $a.$b.$c;
?>
This outputs 111.
Mike Fotes
09-Jul-2005 11:46
In conditional assignment of variables, be careful because the strings may take over the value of the variable if you do something like this:
<?php
$condition = true;
echo "test" . ($condition) ? " <-- That should say test" : "";
?>
You will need to enclose the conditional statement and assignments in parenthesis to have it work correctly:
<?php
$condition = true;
echo "test" . (($condition) ? " <-- That should say test " : "");
?>
josh at PraxisStudios dot com
17-May-2005 01:06
As with echo, you can define a variable like this:
<?php
$text = <<<END
<table>
<tr>
<td>
$outputdata
</td>
</tr>
</table>
END;
?>
The closing END; must be on a line by itself (no whitespace).
user at host dot network
01-May-2005 05:17
pay attention using spaces, dots and parenthesis in case kinda like..
$var=($number>0)?1.'parse error':0.'here too';
the correct form is..
$var=($number>0)?1 .'parse error':0 .'here too';
or
$var=($number>0)?(1).'parse error':(0).'here too';
or
$var = ($number > 0) ? 1 . 'parse error' : 0 . 'here too';
etc..
i think that's why the parser read 1. and 0. like decimal numbers not correctly written, point of fact
$var=$number>0?1.0.'parse error':0.0.'here too';
seems to work correctly..
david at rayninfo dot co dot uk
25-Apr-2005 04:01
When constructing strings from text and variables you can use curly braces to "demarcate" variables from any surrounding text where, for whatever reason, you cannot use a space eg:
$str="Hi my name is ${bold}$name bla-bla";
which AFAIK is the same as
$str="Hi my name is {$bold}$name bla-bla";
zzapper
mike at go dot online dot pt
07-Apr-2005 09:18
In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:
<?php
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");
$num = 1;
$cell = 2;
echo ${foo.$num}[$cell]; $num = 2;
$cell = 0;
echo ${foo.$num}[$cell]; ?>
lucas dot karisny at linuxmail dot org
14-Feb-2005 04:42
Here's a function to get the name of a given variable. Explanation and examples below.
<?php
function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
{
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
?>
Explanation:
The problem with figuring out what value is what key in that variables scope is that several variables might have the same value. To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match. Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.
Examples:
1. Use of a variable contained in the global scope (default):
<?php
$my_global_variable = "My global string.";
echo vname($my_global_variable); ?>
2. Use of a local variable:
<?php
function my_local_func()
{
$my_local_variable = "My local string.";
return vname($my_local_variable, get_defined_vars());
}
echo my_local_func(); ?>
3. Use of an object property:
<?php
class myclass
{
public function __constructor()
{
$this->my_object_property = "My object property string.";
}
}
$obj = new myclass;
echo vname($obj->my_object_property, $obj); ?>
jospape at hotmail dot com
04-Feb-2005 11:45
$id = 2;
$cube_2 = "Test";
echo ${cube_.$id};
// will output: Test
ringo78 at xs4all dot nl
14-Jan-2005 12:27
<?
$filename0="k";
$filename1="kl";
$filename2="klm";
$i=0;
for ($varname = sprintf("filename%d",$i); isset ( ${$varname} ) ; $varname = sprintf("filename%d", $i) ) {
echo "${$varname} <br>";
$varname = sprintf("filename%d",$i);
$i++;
}
?>
Carel Solomon
07-Jan-2005 03:02
You can also construct a variable name by concatenating two different variables, such as:
<?
$arg = "foo";
$val = "bar";
${$arg . $val} = "working";
echo $foobar; echo ${$arg . $val}; ?>
Carel
raja shahed at christine nothdurfter dot com
25-May-2004 10:58
<?php
error_reporting(E_ALL);
$name = "Christine_Nothdurfter";
$$name = "'s students of Tyrolean language ";
print " $name{$$name}<br>";
print "$name$Christine_Nothdurfter";
?>
webmaster at surrealwebs dot com
09-Mar-2004 12:31
OK how about a practicle use for this:
You have a session variable such as:
$_SESSION["foo"] = "bar"
and you want to reference it to change it alot throughout the program instaed of typing the whole thing over and over just type this:
$sess =& $_SESSION
$sess['foo'] = bar;
echo $sess['foo'] // returns bar
echo $_SESSION["foo"] // also returns bar
just saves alot of time in the long run
also try $get = $HTTP_GET_VARS
or $post = $HTTP_POST_VARS
webmaster at daersys dot net
20-Jan-2004 08:15
In reference to "remco at clickbizz dot nl"'s note I would like to add that you don't necessarily have to escape the dollar-sign before a variable if you want to output it's name.
You can use single quotes instead of double quotes, too.
For instance:
<?php
$var = "test";
echo "$var"; echo "\$var"; echo '$var'; ?>
Why?
Well, the reason for this is that the PHP Parser will not attempt to parse strings encapsulated in single quotes (as opposed to strings within double quotes) and therefore outputs exactly what it's being fed with :)
To output the value of a variable within a single-quote-encapsulated string you'll have to use something along the lines of the following code:
<?php
$var = 'test';
echo '$var = "' . $var . '"';
?>
HTH
- Daerion
unleaded at nospam dot unleadedonline dot net
14-Jan-2003 06:37
References are great if you want to point to a variable which you don't quite know the value yet ;)
eg:
$error_msg = &$messages['login_error']; // Create a reference
$messages['login_error'] = 'test'; // Then later on set the referenced value
echo $error_msg; // echo the 'referenced value'
The output will be:
test
| |
| | Citas célebres | La duración de una película debería ser directamente proporcional a la capacidad de la vejiga humana. Alfred Hitchcock Director británico (1899-1980) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... En el colegio | | Falta | El maestro le pregunta a Juanito:
- ¿Por qué no viniste ayer?
- Es que se murió mi abuelo.
- Está bien, pero que no se vuelva a repetir. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|