Johan Fredrik Varen
Johan Fredrik Varen

Reputation: 3914

Alternative syntax for accessing a class variable in PHP

I just stumbled upon an interesting syntax in a PHP script:

echo $foo->{'bar'};

$foo in this case is an object returned from PHP's json_decode() function, but it works well when accessing public members of any object.

I've tried to find out why this syntax was used instead of the more common:

echo $foo->bar;

Does accessing a class member with the syntax from the first example offer anything special, compared to the second example?

Upvotes: 2

Views: 198

Answers (3)

Luca Matteis
Luca Matteis

Reputation: 29267

The curly bracket syntax is useful when you want to reference a function name as a string:

print $foo->{'aMemberFunc'}();

When you want access members which name is provided by another function (or a variable).

Here getVarName() returns a string which can be used to reference a member inside the $foo object.

print $foo->{getVarName()};

Without the curly brackets it would be $foo->getVarName() and it would try and run that method... with the curly brackets it takes a completely different meaning.

echo $foo->{'bar'}; and echo $foo->bar; are identical as far as I can tell.

Upvotes: 4

emurano
emurano

Reputation: 973

The benefit is that you can have variables names that don't adhere to the rules for naming member variables.

This might seem like a bad idea and usually it is but there are uses for it. An example would be if you were writing an application that allowed its users to add arbitrary fields with human readable names but still be accessible for plugins etc.

Upvotes: 0

dev-null-dweller
dev-null-dweller

Reputation: 29462

first syntax allows you to access properties with '-', often used in JSON.

Upvotes: 1

Related Questions