tags:

views:

90

answers:

4

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?

+1  A: 

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;
alex
Hope you don't mind - I misunderstood the first time I read it.
Draemon
Don't mind an upvote? That's OK.
alex
+1  A: 

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

${"test_somethingelse"};

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"};

Chacha102
+9  A: 

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';

To 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 is 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';
Andrew Moore
I need one more accepted answer! Damn You!
Chacha102
Please remember that variable variables are usually a bad idea since it is usually the job of arrays (or objects) to do the job.
Till Theis
+2  A: 

They are 'variable variables'. See this.

Augusto