PHP: Переменные переменные - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Переменные вне PHP Область видимости переменной

Last updated: Sat, 27 Jan 2007

view this page in

# Переменные переменные

Иногда бывает удобно иметь переменными имена переменных. То есть, имя переменной, которое может быть определено и изменено динамически. Обычная переменная определяется примерно таким выражением:

`<?php $a = "hello"; ?>`

Переменная переменная берет значение переменной и рассматривает его как имя переменной. В вышеприведенном примере hello может быть использовано как имя переменной при помощи двух знаков доллара. То есть:

`<?php $$a = "world"; ?>`

Теперь в дереве символов PHP определены и содержатся две переменные: `$a`, содержащая "hello", и `$hello`, содержащая "world". Таким образом, выражение

`<?php echo "$a ${$a}"; ?>`

выведет то же, что и

`<?php echo "$a $hello"; ?>`

то есть, они оба выведут: `hello world`.

Для того чтобы использовать переменные переменные с массивами, вы должны решить проблему двусмысленности. То есть, если вы напишете `$$a[1]`, обработчику необходимо знать, хотите ли вы использовать `$a[1]` в качестве переменной, либо вам нужна как переменная `$$a`, а затем ее индекс [1]. Синтаксис для разрешения этой двусмысленности таков: `${$a[1]}` для первого случая и `${$a}[1]` для второго.

Внимание
Пожалуйста, обратите внимание, что переменные переменные не могут использоваться с Суперглобальными массивами PHP. Это означает, что вы не можете делать что-то вроде `${$_GET}`. Если вы ищете способ использовать суперглобальные переменные и старые `HTTP_*_VARS`, вы можете попробовать ссылаться на них.

add a note User Contributed Notes
Переменные переменные
mikeq
01-Nov-2006 01:44
`Regarding the last post about accessing an array key within a variable variable. The answer is at the bottom of the original help text.
In your example you would do
print ${$superGlobal}['Name'];
This would get you the value from the $_POST array without the need to define another local variable.`
Typer85 at gmail dot com
09-Sep-2006 04:48
`In regards to using variables variables on a
variable of type array;
I found that when using variable variables on a
SuperGlobal such as $_POST or $_GET, which
are in essense arrays, PHP refuses to
access their elements, instead complaining
that an undefined
variable exists.
This is evident even with the little tweaks to below.
For example, using "mot at tdvniikp dot ru"
tweak below ( thanks you saved a lot of trouble )
variable Variable SuperGlobals worked
great.
----------------------------------------
<?php
$superGlobal = '_POST';
global $$superGlobal;
print_r( $$superGlobal );
?>
----------------------------------------
The above code will with success provide an
output of every key in the $_POST SuperGlobal along
with its values.
But here is where the problem comes in. What if I
wanted to access a key from the variable variable,
as illustrated in the following example.
----------------------------------------
<?php
$superGlobal = '_POST';
global $$superGlobal;
// This Would Not Work!
echo $$superGlobal[ 'Name' ];
?>
----------------------------------------
As you can see, I am assuming that a key in
the $_POST SuperGlobal by the name of 'Name' exists,
possibly from a form submission.
Here is the problem; PHP will fail to access this key.
You will get an E_NOTICE error that an undefined
variable exists.
Notice I said an UNDEFINED VARIABLE, not
UNDEFINED INDEX. PHP will assume that there is
no such variable named $_POST at all. I do not know
if this is a bug or is intended but I found a quick workaround.
The workaround is simple. Instead of opting to
access a key from the variable variable
SuperGlobal, you simply just copy the
contents of the variable variable into a
normal variable. Then opt to use it as you
would normally.
The following example shows what I mean.
----------------------------------------
<?php
$superGlobal = '_POST';
global $$superGlobal;
/*
* By assigning our variable variable in a normal non
* dynamic variable, we can now access array keys
* with no problem.
*/
$newSuperGlobal = $$superGlobal;
// This Would Now Work :).
echo $newSuperGlobal[ 'name' ];
?>
----------------------------------------
I will assume that this concept applies to
not only variable variable SuperGlobals,
but variable variable arrays in general,
since like I pointed out before, most
SuperGlobals are in essense arrays.
I hope this saved people some trouble.`
work_at_inarad.ro
28-Jul-2006 04:49
`This is how to declare a class from a string that contain the classname.
class m{
function m($msg="I am the class `m`<br>"){
echo $msg;
}
}
function message(){
return "Class declared with this string!<br>";
}
$classCall="m"; //this variable will contain the class name
$n=new $classCall; //initiate class
$k=new $classCall(message()); //initiate class with parameters`
mot at tdvniikp dot ru
05-May-2006 08:41
`You can simple access Globals by variable variables in functions, example:
<?php
function abc() {
$context = '_SESSION';
global $$context;
if(isset($$context)) {
var_dump($$context);
}
}
abc();
?>`
jkimball4 [at) gmail (dot] c.o.m
10-Mar-2006 11:49
`The correct code for the previous entry is:
<?php
class foo
{
public $thing1 = 'a';
public $thing2 = 'b';
public $thing3 = 'c';
public function getThing1()
{
return $this->thing1;
}
public function getThing2()
{
return $this->thing2;
}
public function getThing3()
{
return $this->thing3;
}
}
$obj = new foo();
for($i=1;$i<=3 ;$i++) {
//note the very small change to the code inside the curly braces.
print $obj->{"getThing".$i}();
}
?>`
bclark <at> digitalbc <dot> net
01-Mar-2006 08:18
`using variable variables to loop through class methods or properties, not all that common, but useful if you need it.
class foo {
public $thing1 = 'a';
public $thing2 = 'b';
public $thing3 = 'c';
public function getThing1() {
return $this->thing1;
}
public function getThing2() {
return $this->thing3;
}
public function getThing3() {
return $this->thing3;
}
}
$obj = new foo();
for($i=0;$i <=3 ;$i++) {
print $obj->{getThing.$i}."\n";
}
output is
a
b
c`
Mephist0 [ Alkon dot com dot ar ]
04-Feb-2006 11:43
`Wrong case :
$a = "hello";
$b = "world";
${$a}{$b} = "Wrong";
or
${$a} . "_" . {$b} = "Wrong";
Case :
${$a . "_" . $b} = "You got it";
print $hello_world; // Prints "You got it";
${$a . $b} = "You got it again";
print $helloworld; // Prints "You got it again";
--------------------------
Simple casses but... very helpfull...`
ptc dot scrcrw at gmail dot com
21-Jan-2006 11:44
`James, dear,
you could have just used <?php extract($_REQUEST); ?>.`
denis at licejus dot lt
10-Jan-2006 11:34
`Note regarding trojjer and James:
Well, isn't import_request_variables made for this already? :)
It is much safer, because it lets you add a prefix to the variable.
<?php
import_request_variables('gp','z');
echo $z_foo;
?>`
fabio at noc dot soton dot ac dot uk
11-Oct-2005 04:15
`A static variable variable sounds like an oxymoron and indeed cannot exist. If you define:
$var = "ciao";
static $$var = 0;
you get a parse error.
Regards,
Fabio`
crap at anitechnic dot com
28-Jul-2005 06:35
`I was trying to move a script from one server to the next, on the first server the $_GET and $_POST were auto declared, but not on the second.
rather than writing out $var = $_POST['var'] a million times I made this script that will turn anything GET'ed or POSTed into a variable.
$getar = $_GET;
$getkeys = array_keys($getar);
for($i=0; $i<count($getkeys); $i++){
$k = $getkeys[$i];
$v = $getar[$k];
${$k}=$v;
}
$getar = $_POST;
$getkeys = array_keys($getar);
for($i=0; $i<count($getkeys); $i++){
$k = $getkeys[$i];
$v = $getar[$k];
${$k}=$v;
}
hope it helps.
James`
Polina
15-Jul-2005 09:13
`Easy way to get a list of items selected by the user, using checkboxes and variable variables.
My form:
<?
include("mysql.inc.php");//my mysql connection
$proSQL = "SELECT * FROM products ORDER BY name"; //selecting products from DB
$pro_query = mysql_query($proSQL) or die($proSQL."<br>".mysql_error());
$pro_num = mysql_num_rows($pro_query); //number of products
print("<form action='theend.php' method='post'>");
$i=0;
while($products = mysql_fetch_object($pro_query)){
$i++;
print("<input type='checkbox' name='$i' value='$products->name'> $products->name<br>"); //print a checkbox with the product name
}
print("<input type='hidden' value='$pro_num' name='products_number'>");//number of products
print("<input type='submit'></form>");
?>
theend.php :
<?
$i=0;
while($i < $products_number){
$i++;
if($$i){
$message .="$$i<br>";
}
}
print("$message");//a list of checked products
?>
This will give a list of the products selected by the user.
I usually use it to send by e-mail with other informations collected from the form.`
rafael at fuchs inf br
21-Mar-2005 08:08
`You can use constants in variable variables, like I show below. This works fine:
<?
define("TEST","Fuchs");
$Fuchs = "Test";
echo TEST . "<BR>";
echo ${TEST};
?>
output:
Fuchs
Test`
Anonymous
13-Mar-2005 07:25
`It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:
<?php
// Given these variables ...
$nameTypes = array("first", "last", "company");
$name_first = "John";
$name_last = "Doe";
$name_company = "PHP.net";
// Then this loop is ...
foreach($nameTypes as $type)
print ${"name_$type"} . "\n";
// ... equivalent to this print statement.
print "$name_first\n$name_last\n$name_company\n";
?>
This is apparent from the notes others have left, but is not explicitly stated.`
Shawn Beltz
03-Mar-2005 12:57
`Forgot to mention, if you want to run the below as one big program, you'll have to undefine $foo in between assignments.`
Shawn Beltz
02-Mar-2005 12:06
`<?php
# Multidimensional variable variables
$foo = "this is foo.";
$ref = "foo";
print $$ref;
# prints "this is foo."
$foo[1]['a_z'] = "this is foo[1][a_z].";
$ref = "foo[1][a_z]";
print $$ref;
# Doesn't print anything!
$foo = "this is foo.";
$ref = "foo";
$erf = eval("return \$$ref;");
print $erf;
# prints "this is foo."
$foo[1]['a_z'] = "this is foo[1][a_z].";
$ref = "foo[1][a_z]";
$erf = eval("return \$$ref;");
print $erf;
# prints "this is foo[1][a_z]."
?>`
28-Jan-2005 04:20
`in response to "pear at inkas dot it"
${$_SESSION['var_name']} does work. What doesn''t work is something like this:
<?php
// consider file has been called with ?var=val
function test() {
$val = '_GET';
var_dump($$a);
echo "\n";
var_dump(${$_GET['var']});
}
test();
?>
will output
NULL
string(4) "_GET"
the use of $$a inside a function or method will not reference the superglobal ever, but instead look for a local variable $_GET, which will never exist, even if you try to create one by doing something like "$_GET = array();" inside the function. setting "global $_GET" inside the function won't work also. You simply can't create a reference to a superglobal inside a function or method by trying to access it via a variable variable.`
sir_hmba AT yahoo DOT com
06-May-2003 03:08
`This is somewhat redundant, but I didn't see an example that combined dynamic reference of *both* object and attribute names.
Here's the code:
//----------------------------------------
class foo
{
var $bar;
var $baz;
function foo()
{
$this->bar = 3;
$this->baz = 6;
}
}
$f = new foo();
echo "f->bar=$f->bar f->baz=$f->baz\n";
$obj = 'f';
$attr = 'bar';
$val = $$obj->{$attr};
echo "obj=$obj attr=$attr val=$val\n";
//----------------------------------------
And here's the output:
f->bar=3 f->baz=6
$obj=f $attr=bar $val=3`
vrillusions at neo dot rr dot com
03-Mar-2003 11:01
`Here is a very simple way of getting items from the $_POST superglobal into seperate variables. I did this so I can easily print information in a form without having to worry about "this value isn't set" messages. will create variables in the form $frm_nameInForm.
foreach($_POST as $key => $value) {
$varname = "frm_".$key;
$$varname = $value;
}
[Editor Note: Instead of this code, you could simply use extract() or import_request_variables() -Philip]`
Dave
07-Feb-2003 12:40
`[Editor's Note]
If you truly want to extract the variables from super globals instead of looping over the array use extract(); or turn register globals on via an .htaccess file so it is enabled only for the script(s) that depend on it.
[End Note]
A lot of the php code out there relies on register_globals being set to "on" in the php.ini -- which may not be an option for some developers. It seems that the following function would attempt to overcome that issue for later versions of php. I haven't tried it out yet, as I have no need for it right now -- and it may pose some of the same issues as if you had register_globals set to "on" -- but here it is, anyway.
function getRequestVariables()
{
foreach ($_POST as $postKey => $postValue)
{
global $$postKey;
$$postKey = trim (stripslashes ($postValue));
}
foreach ($_GET as $getKey => $getValue)
{
global $$getKey;
if (empty($$getKey))
{
$$getKey = trim (stripslashes ($getValue));
}
}
}`
info at gieson dot com
17-Oct-2002 08:22
`I needed to dynamically evaluate a varible.... i wanted to create the name of the variable on the fly and then get it's value. In other words, I wanted to dynamically build the name of a variable, and then evaluate it.
Example:
These items already exists:
$var1 = "bird";
$var2 = "cat";
$var3 = "dog";
... let's say there are 3 million of these variables in a series...
Now i want to find out which var has a value of "dog" - so i need to dynamically build the name of the variable. You can do the FOR loop thing to create a string that represents the name of the variable, but how on earth do you evaluate a string as if it were a variable? enter "variable variables"
for ($i=0; $i<4; $i++){
//create the label of the variable;
$var_label_string = "var$i";
//Now evaluate that string as if it were a variable !;
$value_of_that_var = ${$var_label_string};
//now find out if that var is equal to "dog";
if ($value_of_that_var == "dog"){
print "Dog found here: $var_label_string";
}
}`
antony dot booth at nodomain dot here
19-Sep-2002 07:17
`You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: -
<?php
foreach ($array as $key => $value)
{
$$key= $value;
}
?>
This however would be reinventing the wheel when you can simply use:
<?php
extract( $array, EXTR_OVERWRITE);
?>
Note that this will overwrite the contents of variables that already exist.
Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: -
EXTR_PREFIX_ALL
<?php
$array =array("one" => "First Value",
"two" => "2nd Value",
"three" => "8"
);
extract( $array, EXTR_PREFIX_ALL, "my_prefix_");
?>
This would create variables: -
$my_prefix_one
$my_prefix_two
$my_prefix_three
containing: -
"First Value", "2nd Value" and "8" respectively`
jupp-mueller at t-online dot de
08-Sep-2002 06:29
`I found another undocumented/cool feature: variable member variables in classes. It's pretty easy:
class foo {
function bar() {
$bar1 = "var1";
$bar2 = "var2";
$this->{$bar1}= "this ";
$this->{$bar2} = "works";
}
}
$test = new foo;
$test->bar();
echo $test->var1 . $test->var2;`
thien_tmpNOSPAM at hotmail dot com
20-Aug-2002 03:37
`You can also use variable variables and the string concat operator to generate suffixed (or prefixed) variables based on a base name.
For instance, if you wanted to dynamically generate this series of variables:
base1_suffix1
base1_suffix2
base2_suffix1
base2_suffix2
base3_suffix1
base3_suffix2
You can do this:
$bases = array('base1', 'base2', 'base3');
$suffixes = array('suffix1', suffix2);
foreach($bases as $base) {
foreach($suffixes as $suffix) {
${$base.$suffix} = "whatever";
#...etc
}
}`
(J. Dyer) jkdyer_at_vlsmaps_com
14-Aug-2002 05:08
`A final note,
I have not seen this anywhere else, and I am unsure exactly where to post this snippet. This is another example from the same program I used in the previous entries.
Essentially, I wanted to make a dynamically generated, multi-dimensional, associative array. The dynamic generation consists of an association within the array of a certain key attribute within those variably-named objects from my previous example.
Yes, there are other, easier ways to associate objects than this manner; however, for this particular project, the snippet is a solution for a requested "feature" on a website. That feature consists of displaying the values from only certain, user-specified objects by their "key" value.
[note: the name of the variables/arrays change from example to example to avoid ambiguity within the script. The $obj_array is the same as the previous $array. Also, there are two different methods to place the $obj object into the array, and this was a trial to see which one worked. They both do.]
<?php
// ...
foreach ($this->obj_array as $key=>$obj){
// if the key already exists..
if ( array_key_exists($obj->GetKeyCode(), $this->new_array) ){
$key = $obj->GetKeyCode();
array_push($this->new_array[$key], $obj);
} // end if
// else if the key doesn't exist, create it.
else{
$key = $obj->GetKeyCode();
$this->new_array[$key] = array();
$this->new_array[$key][] = $obj;
} // end else
} // end foreach
//...
?>`
(J. Dyer) jkdyer_at_vlsmaps_com
13-Aug-2002 09:32
`... to continue my previous example of placing dynamically named objects into an array, we can easily pull everything back out again using a basic array function: foreach.
<?php
//...
foreach($array as $key=>$object){
echo $key." -- ".$object->print_fcn()." <br/>\n";
} // end foreach
?>
Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.`
J. Dyer
12-Aug-2002 01:05
`Another use for this feature in PHP is dynamic parsing..
Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created. In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.
Normally, you won't need something this convolute. In this example, I needed to load an array with dynamically named objects - (yes, this has some basic Object Oriented programming, please bare with me..)
<?php
include("obj.class");
// this is only a skeletal example, of course.
$object_array = array();
// assume the $input array has tokens for parsing.
foreach ($input_array as $key=>$value){
// test to ensure the $value is what we need.
$obj = "obj".$key;
$$obj = new Obj($value, $other_var);
Array_Push($object_array, $$obj);
// etc..
}
?>
Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.
I haven't fully tested the implimentation of the objects. The scope of a variable-variable's object attributes (get all that?) is a little tough to crack. Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.`
adamhooper at videotron dot ca
09-Aug-2002 03:35
`A lot of people use this feature when it's not really necessary or recommended. Instead of using $var1, $var2, $var3, etc, just use the array $var[]. Arrays can be used in HTML forms too.`
John
18-Jul-2002 04:12
`A string that looks like an array can be used as a variable variable, but it won't equal the array value. Very odd. It defies the naming rules.
$one[1] = 'John';
$two = 'one[1]';
echo "one={$one[1]} two={$$two}<br>"; // => one=John two=
$$two = "Doe";
echo "one={$one[1]} two={$$two}<br>"; // => one=John two=Doe`
04-Jun-2002 11:34
`/*The 'dollar dereferencing' (to coin a phrase) doesn't seem to be limited to two layers, even without curly braces. Observe:*/
$one = "two";
$two = "three";
$three = "four";
$four = "five";
echo $$$$one; //prints 'five'.
/*This works for L-values as well. So the below works the same way:*/
$one = "two";
$$one = "three";
$$$one = "four";
$$$$one = "five";
echo $$$$one; //still prints 'five'.
/*NOTE: PHP 4.2.1, Apache 2.0.36, Red Hat 7.2*/`
24-May-2002 04:21
`//to reference cells and place them in a table format
//for exmple cells named ref1_1, ref1_2, ref1_3, ref1_4, ref2_1 ... through ref4_4
print "<table border=\"0\"><tr><td valign=\"top\" >\n ";
for($i=1;$i<5;$i++)
{
for($h=1;$h<5;$h++)
{
$cellname = "ref$i"."_"."$h";
print ($a_row->{$cellname});
print "</td>";
if ($h==4) print "</tr><tr> \n";
print "<td valign=\"top\" > \n";
}
}
print "</td></tr></table>\n";`
chrisNOSPAM at kampmeier dot net
08-Aug-2001 10:40
`Note that normal variable variables will not be parsed in double-quoted strings. You'll have to use the braces to make it work, to resolve the ambiguity. For example:
$varname = "foo";
$foo = "bar";
print $$varname; // Prints "bar"
print "$$varname"; // Prints "$foo"
print "${$varname}"; // Prints "bar"`
phil at NO^SPAMw30wnzj00 dot com
21-Jun-2001 03:19
`Expanding on the variable function note a bit:
when using variable methods the syntax is a bit different. to call a function whose name is contained in $var_func:
$this->$var_func($parm1, $parm2);
thus...
class A
{
function f1($parm){echo $parm;}
}
$objA = new A();
$var_func = 'f1';
$objA->$var_func("moo");
produces 'moo'`
mstearne at entermix dot com
10-May-2001 06:09
`Variable variables techniques do not work when one of the "variables" is a constant. The example below illustrates this. This is probably the desired behavior for constants, but was confusing for me when I was trying to figure it out. The alternative I used was to add the variables I needed to the $GLOBALS array instead of defining them as constants.
<?php
define("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";
function connectTo($databaseName){
global $DB_Z_NAME;
$fullDatabaseName="DB_".$databaseName."_NAME";
return ${$fullDatabaseName};
}
print "DB_X_NAME is ".connectTo("X")."<br>";
print "DB_Y_NAME is ".connectTo("Y")."<br>";
print "DB_Z_NAME is ".connectTo("Z")."<br>";
?>
[Editor Note: For variable constants, use constant() --Philip]`
bpotier at edreamers dot org
26-Feb-2001 09:11
`A good example of the use of variable variables name. Imagine that you want to modify at the same time a list of more than one record from a db table.
1) You can easily create a dynamic form using PHP. Name your form elements using a static name and the record id
ex: <input name="aninput<?php echo $recordid?>" which gives in the output something like <input name="aninput15">
2)You need to provide to your form action/submit script the list of records ids via an array serialized and urlencoded via an hidden field (to decode and un serialize once in the submit script)
3) In the script used to submit you form you can access the input value by using the variable ${'aninput'.$recordid} to dynamically create as many UPDATE query as you need
[Editor Note: Simply use an array instead, for example: <input name="aninput[<?php echo $recordid?>]" And loop through that array. -Philip]`
dnl at au dot ru
08-Dec-2000 11:01
`By the way...
Variable variables can be used as pointers to objects' properties:
<?
class someclass {
var $a = "variable a";
var $b = "another variable: b";
}
$c = new someclass;
$d = "b";
echo $c->{$d};
?>
outputs: another variable: b`
mccoyj at mail dot utexas dot edu
03-Nov-2000 03:36
`There is no need for the braces for variable object names...they are only needed by an ambiguity arises concerning which part of the reference is variable...usually with arrays.
class Schlemiel {
var $aVar = "foo";
}
$schlemiel = new Schlemiel;
$a = "schlemiel";
echo $$a->aVar;
This code outputs "foo" using PHP 4.0.3.
Hope this helps...
- Jordan`
add a note
Переменные вне PHP Область видимости переменной

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST