PHP curly brace syntax for member variable

David Weinraub picture David Weinraub · Jul 18, 2009 · Viewed 35.5k times · Source

First question on SO and it's a real RTM candidate. But I promise you I've looked and can't seem to find it. I'll happily do a #headpalm when it turns out to be a simple thing that I missed.

Trying to figure out Zend Framework and came across the following syntax:

$this->_session->{'user_id'}

I have never seen the curly braces syntax used to access what appears to be a member variable. How is it different than

$this->_session->user_id

I'm assuming that the _session is irrelevant, but including it in the question since it may not be.

Are the curly braces just a cleanliness convention that attempts to wrap the compound variable name user_id? Or is it some kind of a special accessor?

Any pointers into TFM so I can R up would be humbly appreciated.

Many thanks. Please be gentle.

Answer

James Skidmore picture James Skidmore · Jul 18, 2009

Curly braces are used to explicitly specify the end of a variable name. For example:

echo "This square is {$square->width}00 centimeters broad."; 

So, your case is really a combination of two special cases. You're allowed to access class variables using curly braces and like so:

$class->{'variable_name'} // Same as $class->variable_name
$class->{'variable' . '_name'} // Dynamic values are also allowed

And in your case, you're just surrounding them with the curly brace syntax.

See the PHP manual, "complex (curly) syntax."