问题描述
只是想知道为什么这样的东西行不通:
Just wondering why something like this doesn't work:
public function address($name){
if(!isset($this->addresses[$name])){
$address = new stdClass();
$address->city = function($class = '', $style = ''){
return $class;
};
$this->addresses[$name] = $address;
}
return $this->addresses[$name];
}
像echo $class->address('name')->city('Class')
那样调用它应该只回显Class
,但是我却得到Fatal error: Call to undefined method stdClass::city()
Calling it like echo $class->address('name')->city('Class')
should just echo Class
, however I get Fatal error: Call to undefined method stdClass::city()
我可以找到一种更好的方法来执行此操作,因为这会变得很混乱,但是我想知道那里可能做错了什么,或者PHP是否不支持此操作以及原因.
I can find a better way to do this, because this will get messy, but I'm wondering what I might be doing wrong there, or if PHP doesn't support this and why.
推荐答案
调用致命错误Call to undefined method stdClass::city()
时PHP是正确的,因为对象$class->address('name')
没有方法 city
.Intead,此对象具有属性 city
,它是Closure类的实例( http ://www.php.net/manual/zh/class.closure.php )您可以验证以下内容:var_dump($class->address('name')->city)
PHP is right when invoke fatal error Call to undefined method stdClass::city()
because object $class->address('name')
has no method city
.Intead, this object has property city
which is instance of Closure Class (http://www.php.net/manual/en/class.closure.php)You can verify this: var_dump($class->address('name')->city)
我发现调用此匿名函数的方法是:
I found the way to call this anonymous function is:
$closure = $class->address('name')->city;
$closure('class');
希望这会有所帮助!
这篇关于在新的stdClass中声明一个匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!