Vous êtes sur la page 1sur 2

Chapter 2: Variables

Section 2.1: Accessing A Variable Dynamically By Name

(Variable variables)

Variables can be accessed via dynamic variable names. The name of a variable can be stored in another
variable,

allowing it to be accessed dynamically. Such variables are known as variable variables.

To turn a variable into a variable variable, you put an extra $ put in front of your variable.

$variableName = 'foo';

$foo = 'bar';

// The following are all equivalent, and all output "bar":

echo $foo;

echo ${$variableName};

echo $$variableName;

//similarly,

$variableName = 'foo';

$$variableName = 'bar';

// The following statements will also output 'bar'

echo $foo;

echo $$variableName;

echo ${$variableName};

Variable variables are useful for mapping function/method calls:

function add($a, $b) {

return $a + $b;

$funcName = 'add';

echo $funcName(1, 2); // outputs 3

This becomes particularly helpful in PHP classes:

class myClass {

public function __construct() {


$functionName = 'doSomething';

$this->$functionName('Hello World');

private function doSomething($string) {

echo $string; // Outputs "Hello World"

It is possible, but not required to put $variableName between {}:

${$variableName} = $value;

The following examples are both equivalent and output "baz":

$fooBar = 'baz';

Vous aimerez peut-être aussi