1

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];
1

3 Answers 3

4
echo $p->{$name};
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. That's easy. Why would the {} be necessary? I mean in what case would they be?
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.
3

echo $p->$name;

Comments

1

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

echo $p->{$name};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.