PHP curly brace syntax for member variable

匆匆过客 提交于 2019-11-26 03:52:37

问题


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.


回答1:


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




回答2:


I know the syntax just when using variable variables:

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



回答3:


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 world\0\n"} 
$this->object->{"function(){   this is a truely awful  name for a variable }"} 



回答4:


The two examples in your question do the same thing. PHP allows you to access member data/methods in several ways...

object->{'name_of_member'};

object->name_of_member;

$member = 'name_of_member';
object->$member;



回答5:


In the example you give, there's no real difference, and IMO $this->_session->user_id should be used because it's clearer.

What the curly brace syntax is actually good for is accessing a member variable by constructing an expression for its name, like $this->_session->{'user_id' . $index}.



来源:https://stackoverflow.com/questions/1147937/php-curly-brace-syntax-for-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!