Tutorial :PHP Syntax ${“{$type}_method”}


I've been reading an PHP5 book, and the author commonly used this syntax


I have no idea what that means. Does it dynamically generate a variable name?

Someone help me out?


It is a language feature called Variable variables.

Consider the following piece of code:

$a = 'hello';  

This is pretty straight forward. It creates the variable $a and sets its value to 'hello'.

Let's move on with:

$$a = 'world';  ${$a} = 'world';  

Basically, since $a = 'hello', those two statement are the equivalent of doing:

$hello = 'world';  

So the following:

echo "$a ${$a}";  

Is the equivalent of doing:

echo "$a $hello";  

Braces { }

The braces are used to prevent ambiguity problems from occurring. Consider the following:

$$a[1] = 'hello world';  

Do you want to assign a variable named after the value of $a[1] or do you want to assign the index 1 of the variable named after $a?

For the first choice, you would write it as such:

${$a[1]} = 'hello world';  

For the second choice:

${$a}[1] = 'hello world';  

Your example

Now, for your example.

Let's consider that:

$something = 'hello';  

Using your example as such:

${"{$something}_somethingelse"} = 'php rocks';  

Would essentially be equivalent of doing:

$hello_somethingelse = 'php rocks';  


They are 'variable variables'. See this.


Brackets allow you to make more advanced variable names. It your Case if $something was equal to test it would be:


Which is just an advanced variable name.

Here is an example.

  $test = "test";  ${"test_test"} = "test2";    echo $test; // prints test  echo ${"test_test"}; // prints test2  

Using Variable Varaibles, as everyone else mentioned, you can create variables based on other variables. So in your case, he was making a variable based on $something's value

  $something = "test";    ${"{$something}_somethingelse"};    turns into    ${"test_somethingelse"};    


That will replace the {$something} with the value of $something.

I think the inner curly braces are just for readability and to help when doing $object->property etc.

Because it seems to be also in a variable, that is called a variable variable.

For example,

$foo = 'bar';    $$foo = 7;    echo $bar;    // produces 7;  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »