PHP curly brace syntax for member variable

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.


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."


我知道使用变量变量时的语法:

$userProp = 'id';
$this->_session->{'user_'.$userProp};

Theres probably one big advantage of that syntax, however, its generally in the domain of hairy stuff, and things you probably want to avoid.

It permits you to use characters in variable names that are otherwise unpermitted.

ie:

$this->object->{"hello worldn"} 
$this->object->{"function(){   this is a truely awful  name for a variable }"} 
链接地址: http://www.djcxy.com/p/10192.html

上一篇: 了解Magento块和块类型

下一篇: PHP成员变量的大括号语法