A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.php.net/manual/en/language.variables.variable.php below:

PHP: Variable variables - Manual

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

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

produces the exact same output as:

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

i.e. they both produce: hello world.

In order to use variable variables with arrays, an ambiguity problem has to be resolved. That is, if the parser sees $$a[1] then it needs to know if $a[1] was meant to be used as a variable, or if $$a was wanted as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if there is an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Curly braces may also be used to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of multiple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

Example #1 Variable property example

<?php
class Foo {
public
$bar = 'I am bar.';
public
$arr = ['I am A.', 'I am B.', 'I am C.'];
public
$r = 'I am r.';
}
$foo = new Foo();
$bar = 'bar';
$baz = ['foo', 'bar', 'baz', 'quux'];
echo
$foo->$bar . "\n";
echo
$foo->{$baz[1]} . "\n";$start = 'b';
$end = 'ar';
echo
$foo->{$start . $end} . "\n";$arr = 'arr';
echo
$foo->{$arr[1]} . "\n";
echo
$foo->{$arr}[1] . "\n";?>

The above example will output:

I am bar.
I am bar.
I am bar.
I am r.
I am B.
Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

userb at exampleb dot org

15 years ago

<?php$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";$a; $$a; $$$a; $$$$a; $$$$$a; $$$$$$a; $$$$$$$a; ?>
sebastopolys at gmail dot com

2 years ago

In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).

This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter


an associative array :
array('index'=>'value','index'=>'value');
index = reference to variable to be used within function
value = name of the variable to be used within function
<?php

$vars

= ['id'=>'user_id','email'=>'user_email'];validateVarsFunction($vars);

function

validateVarsFunction($vars){$user_id=21;
$user_email='email@mail.com';

echo

$vars['id']; echo ${$vars['id']}; echo 'Email: '.${$vars['email']}; }
?>
Anonymous

20 years ago

It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:

<?php
$nameTypes = array("first", "last", "company");
$name_first = "John";
$name_last = "Doe";
$name_company = "PHP.net";foreach($nameTypes as $type)
print ${
"name_$type"} . "\n";print "$name_first\n$name_last\n$name_company\n";
?>


This is apparent from the notes others have left, but is not explicitly stated.
marcin dot dzdza at gmail dot com

6 years ago

The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It's a kind of magic :) This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking "$userName". You may easily omit:
$a = 'username';
echo $$a;

herebepost (ta at ta) [iwonderr] gmail dot com

9 years ago

While not relevant in everyday PHP programming, it seems to be possible to insert whitespace and comments between the dollar signs of a variable variable. All three comment styles work. This information becomes relevant when writing a parser, tokenizer or something else that operates on PHP syntax.

<?php

$foo

= 'bar';
$
$foo = 'magic';

echo

$bar; ?>


Behaviour tested with PHP Version 5.6.19
jefrey.sobreira [at] gmail [dot] com

10 years ago

If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:

<?php
$price_for_monday
= 10;
$price_for_tuesday = 20;
$price_for_wednesday = 30;$today = 'tuesday';$price_for_today = ${ 'price_for_' . $today};
echo
$price_for_today; ?>

Sinured

18 years ago

One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.

<?php
define
('ONE', 1);
function
one() {
return
1;
}
$one = 1;

${

"foo$one"} = 'foo';
echo
$foo1; ${'foo' . ONE} = 'bar';
echo
$foo1; ${'foo' . one()} = 'baz';
echo
$foo1; ?>


This syntax doesn't work for functions:

<?php
$foo
= 'info';
{
"php$foo"}(); $func = "php$foo";
$func();
?>


Note: Don't leave out the quotes on strings inside the curly braces, PHP won't handle that graciously.
mason

15 years ago

PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

<?php
class Foo {
public function
hello() {
echo
'Hello world!';
}
}
$my_foo = 'Foo';
$a = new $my_foo();
$a->hello(); ?>


Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

<?php
class Foo {
public static function
hello() {
echo
'Hello world!';
}
}
$my_foo = 'Foo';
$my_foo::hello(); ?>

nils dot rocine at gmail dot com

13 years ago

Variable Class Instantiation with Namespace Gotcha:

Say you have a class you'd like to instantiate via a variable (with a string value of the Class name)

<?phpclass Foo
{
public function
__construct()
{
echo
"I'm a real class!" . PHP_EOL;
}
}
$class = 'Foo';$instance = new $class;?>


The above works fine UNLESS you are in a (defined) namespace. Then you must provide the full namespaced identifier of the class as shown below. This is the case EVEN THOUGH the instancing happens in the same namespace. Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.)

<?phpnamespace MyNamespace;

class

Foo
{
public function
__construct()
{
echo
"I'm a real class!" . PHP_EOL;
}
}
$class = 'MyNamespace\Foo';$instance = new $class;?>

Nathan Hammond

17 years ago

These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent upon the current scope.

<?php

$_POST

['asdf'] = 'something';

function

test() {
$string = '_POST';
var_dump(${$string});var_dump(${'_POST'});global ${$string};
var_dump(${$string});

}

$string = '_POST';
var_dump(${$string});test();?>


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4