Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Syntax ${"{$type}_method"}

Tags:

php

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

${"{$something}_somethingelse"};

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

Someone help me out?

like image 435
Zack Avatar asked Dec 06 '25 17:12

Zack


2 Answers

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';
like image 167
Andrew Moore Avatar answered Dec 08 '25 09:12

Andrew Moore


They are 'variable variables'. See this.