[EDIT by danbrown AT php DOT net: The function provided by this author will give you all defined variables at runtime. It was originally written by (john DOT t DOT gold AT gmail DOT com), but contained some errors that were corrected in subsequent posts by (ned AT wgtech DOT com) and (taliesin AT gmail DOT com).]
<?php
echo '<table border=1><tr> <th>variable</th> <th>value</th> </tr>';
foreach( get_defined_vars() as $key => $value)
{
if (is_array ($value) )
{
echo '<tr><td>$'.$key .'</td><td>';
if ( sizeof($value)>0 )
{
echo '"<table border=1><tr> <th>key</th> <th>value</th> </tr>';
foreach ($value as $skey => $svalue)
{
echo '<tr><td>[' . $skey .']</td><td>"'. $svalue .'"</td></tr>';
}
echo '</table>"';
}
else
{
echo 'EMPTY';
}
echo '</td></tr>';
}
else
{
echo '<tr><td>$' . $key .'</td><td>"'. $value .'"</td></tr>';
}
}
echo '</table>';
?>
Variáveis
Índice
Introdução
As variáveis no PHP são representadas por um cifrão ($) seguido pelo nome da variável. Os nomes de variável no PHP fazem distinção entre maiúsculas e minúsculas.
Os nomes de variável seguem as mesmas regras como outros rótulos no PHP. Um nome de variável válido se inicia com uma letra ou sublinhado, seguido de qualquer número de letras, algarismos ou sublinhados. Em uma expressão regular isto poderia ser representado desta forma: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Nota: Para nosso propósito, as letras a-z, A-Z e os bytes de 127 a 255 (0x7f-0xff).
Nota: $this é uma variável especial que não pode ser atribuída.
Veja também o Guia de nomenclatura em espaço de usuário.
Para informação sobre funções relacionadas a variáveis, veja a Referência de funções para variáveis.
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // exibe "Bob, Joe"
$4site = 'not yet'; // inválido; começa com um número
$_4site = 'not yet'; // válido; começa com um sublinhado
$täyte = 'mansikka'; // válido; 'ä' é um caracter ASCII (extendido) 228
?>
Por padrão, as variáveis são sempre atribuídas por valor. Isto significa que quando você atribui uma expressão a uma variável, o valor da expressão original é copiado integralmente para a variável de destino. Isto significa também que, após atribuir o valor de uma variável a outra, a alteração de uma destas variáveis não afetará a outra. Para maiores informações sobre este tipo de atribuição, veja o capítulo em Expressões.
O PHP oferece um outro meio de atribuir valores a variáveis: atribuição por referência. Isto significa que a nova variável simplesmente referencia (em outras palavras, "torna-se um apelido para" ou "aponta para") a variável original. Alterações na nova variável afetam a original e vice versa.
Para atribuir por referência, simplesmente adicione um e-comercial (&) na frente do nome da variável que estiver sendo atribuída (variável de origem) Por exemplo, o trecho de código abaixo imprime 'My name is Bob' duas vezes:
<?php
$foo = 'Bob'; // Atribui o valor 'Bob' a variável $foo
$bar = &$foo; // Referecia $foo através de $bar.
$bar = "My name is $bar"; // Altera $bar...
echo $bar;
echo $foo; // $foo é alterada também.
?>
Uma observação importante a se fazer: somente variáveis nomeadas podem ser atribuídas por referência.
<?php
$foo = 25;
$bar = &$foo; // Esta atribuição é válida.
$bar = &(24 * 7); // Inválido; referencia uma expressão sem nome.
function test()
{
return 25;
}
$bar = &test(); // Inválido.
?>
Não é necessário variáveis inicializadas no PHP, contudo é uma ótima prática. Variáveis não inicializadas tem um valor padrão do tipo dela dependendo do contexto no qual eles são usados - padrão de booleanos é FALSE, de inteiros e ponto-flutuantes é zero, strings (e.g. usado em echo()) são definidos como uma string vazia e arrays tornam-se um array vazio.
Exemplo #1 Valores padrões de variáveis não inicializadas
<?php
// Limpa e remove referência (sem uso de contexto) a variável; imprime NULL
var_dump($unset_var);
// Uso de booleano; imprime 'false' (Veja sobre operadores ternário para saber mais sobre a sintaxe)
echo ($unset_bool ? "true" : "false"); // false
// Uso de string; imprime 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);
// Uso de inteiro; imprime 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);
// Uso de float/double; imprime 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);
// Uso de array; imprime array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);
// Uso de objeto; cria novo objeto stdClass (veja http://www.php.net/manual/en/reserved.classes.php)
// Imprime: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>
Confiar no valor padrão de uma variável não inicializada é problemático no caso de incluir um arquivo em outro que usa variável com mesmo nome. E também um principal risco de segurança com register_globals estando on. Erros E_NOTICE são emitidos no caso de ter variáveis não inicializadas, contudo não no caso de adicionar elementos para um array não inicializado. O construtor da linguagem isset() pode ser usado para detectar se uma variável não foi inicializada.
Variáveis
20-Jul-2008 03:25
07-Jul-2007 06:13
Here's a simple solution for retrieving the variable name, based on the lucas (http://www.php.net/manual/en/language.variables.php#49997) solution, but shorter, just two lines =)
<?php
function var_name(&$var, $scope=0)
{
$old = $var;
if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;
}
?>
20-Feb-2007 05:48
As an addendum to David's 10-Nov-2005 posting, remember that curly braces literally mean "evaluate what's inside the curly braces" so, you can squeeze the variable variable creation into one line, like this:
<?php
${"title_default_" . $title} = "selected";
?>
and then, for example:
<?php
$title_select = <<<END
<select name="title">
<option>Select</option>
<option $title_default_Mr value="Mr">Mr</option>
<option $title_default_Ms value="Ms">Ms</option>
<option $title_default_Mrs value="Mrs">Mrs</option>
<option $title_default_Dr value="Dr">Dr</option>
</select>
END;
?>
25-Jan-2007 11:10
Here's a pair of functions to encode/decode any string to be a valid php and javascript variable name.
<?php
function label_encode($txt) {
// add Z to the begining to avoid that the resulting
// label is a javascript keyword or it starts with a
// number
$txt = 'Z'.$txt;
// encode as urlencoded data
$txt = rawurlencode($txt);
// replace illegal characters
$illegal = array('%', '-', '.');
$ok = array('é', 'è', 'à');
$txt = str_replace($illegal,$ok, $txt);
return $txt;
}
function label_decode($txt) {
// replace illegal characters
$illegal = array('%', '-', '.');
$ok = array('é', 'è', 'à');
$txt = str_replace($ok, $illegal, $txt);
// unencode
$txt = rawurldecode($txt);
// remove the leading Z and return
return substr($txt,1);
}
?>
20-May-2006 02:44
Simple sample and variables and html "templates":
The PHP code:
variables.php:
<?php
$SYSN["title"] = "This is Magic!";
$SYSN["HEADLINE"] = "Ez magyarul van"; // This is hungarian
$SYSN["FEAR"] = "Bell in my heart";
?>
index.php:
<?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
25-Nov-2005 11:03
References and "return" can be flakey:
<?php
// This only returns a copy, despite the dereferencing in the function definition
function &GetLogin ()
{
return $_SESSION['Login'];
}
// This gives a syntax error
function &GetLogin ()
{
return &$_SESSION['Login'];
}
// This works
function &GetLogin ()
{
$ret = &$_SESSION['Login'];
return $ret;
}
?>
10-Nov-2005 10:25
When using variable variables this is invalid:
<?php
$my_variable_{$type}_name = true;
?>
to get around this do something like:
<?php
$n="my_variable_{$type}_name";
${$n} = true;
?>
(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...)
31-Aug-2005 02:09
Variables can also be assigned together.
<?php
$a = $b = $c = 1;
echo $a.$b.$c;
?>
This outputs 111.
09-Jul-2005 08: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;
// Outputs " <-- That should say test"
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;
// Outputs "test <-- That should say test"
echo "test" . (($condition) ? " <-- That should say test " : "");
?>
17-May-2005 10: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).
[EDIT by danbrown AT php DOT net: This note illustrates HEREDOC syntax. For more information on this and similar features, please read the "Strings" section of the manual here: http://www.php.net/manual/en/language.types.string.php ]
07-Apr-2005 06:18
In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:
<?php
//considering 2 arrays
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");
//and 2 variables that hold integers
$num = 1;
$cell = 2;
echo ${foo.$num}[$cell]; // outputs "c"
$num = 2;
$cell = 0;
echo ${foo.$num}[$cell]; // outputs "d"
?>
15-Feb-2005 01: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); // Outputs: 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(); // Outputs: my_local_variable
?>
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); // Outputs: my_object_property
?>
05-Feb-2005 08:45
<?php
$id = 2;
$cube_2 = "Test";
echo ${cube_.$id};
// will output: Test
?>
14-Jan-2005 09:27
<?php
// I am beginning to like curly braces.
// I hope this helps for you work with them
$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++;
}
?>
07-Jan-2005 12:02
You can also construct a variable name by concatenating two different variables, such as:
<?php
$arg = "foo";
$val = "bar";
//${$arg$val} = "in valid"; // Invalid
${$arg . $val} = "working";
echo $foobar; // "working";
//echo $arg$val; // Invalid
//echo ${$arg$val}; // Invalid
echo ${$arg . $val}; // "working"
?>
Carel
25-May-2004 07:58
<?php
error_reporting(E_ALL);
$name = "Christine_Nothdurfter";
// not Christine Nothdurfter
// you are not allowed to leave a space inside a variable name ;)
$$name = "'s students of Tyrolean language ";
print " $name{$$name}<br>";
print "$name$Christine_Nothdurfter";
// same
?>
20-Jan-2004 05:15
You don't necessarily have to escape the dollar-sign before a variable if you want to output its name.
You can use single quotes instead of double quotes, too.
For instance:
<?php
$var = "test";
echo "$var"; // Will output the string "test"
echo "\$var"; // Will output the string "$var"
echo '$var'; // Will do the exact same thing as the previous line
?>
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';
/*
Using single quotes here seeing as I don't need the parser to actually parse the content of this variable but merely treat it as an ordinary string
*/
echo '$var = "' . $var . '"';
/*
Will output:
$var = "test"
*/
?>
HTH
- Daerion
15-Jan-2003 03:37
References are great if you want to point to a variable which you don't quite know the value yet ;)
eg:
<?php
$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
