views:

40

answers:

3

I have a Persons object. It has a variable name accessible by saying

$p = new Person('John');
echo $p->name;

Now I have a string.

$name = 'name';

I need to get $p->name using $p and $name. Something like

echo $p->[$name];
+4  A: 
echo $p->{$name};
LeguRi
Wow. That's easy. Why would the `{}` be necessary? I mean in what case would they be?
Josh K
If you want to go all out with something like `$p->{functionA(functionB().$name)}` but it's a bit excessive ;) I also find it easier to read. `$p->$name` looks too much like `$p-$name`.
LeguRi
+2  A: 

echo $p->$name;

draganHR
A: 

echo $p->$name; may generates error if it contains special characters so following one is perfect

echo $p->{$name};
kodegeek