PHP 实例化后类成员的闭包产生未定义的方法
我试图将 ACL 破解到模板中,而不使模板知道类定义中的 ACL 对象。下面的代码生成了一个未定义的方法 Template::isAllowed
这是为什么?蒂亚!
class ACL {
protected $allowed = array('anything');
public function isAllowed($what){
if(in_array($what, $this->allowed))
return true;
return false;
}
}
class Template extends stdClass { }
$Template = new Template;
$ACL = new ACL;
$Template->isAllowed = function($what) use($ACL) { return $ACL->isAllowed($what); };
if($Template->isAllowed('anything'))
echo 1;
else
echo 2;
I am trying to hack an ACL into a Template without making the Template aware of the ACL object in the class definition. The following code generates an undefined method Template::isAllowed
Why is this? TIA!
class ACL {
protected $allowed = array('anything');
public function isAllowed($what){
if(in_array($what, $this->allowed))
return true;
return false;
}
}
class Template extends stdClass { }
$Template = new Template;
$ACL = new ACL;
$Template->isAllowed = function($what) use($ACL) { return $ACL->isAllowed($what); };
if($Template->isAllowed('anything'))
echo 1;
else
echo 2;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这:
实际上告诉 PHP 调用一个方法
Template::isAllowed()
,该方法显然不存在,如您的致命错误所示。您不能通过将闭包分配给属性来将
Template::isAllowed()
视为真正的方法。但是,您仍然可以调用分配给$Template->isAllowed
属性的闭包(这是闭包
)。为此,您需要将该属性分配给变量,然后调用该变量:或者使用 call_user_func():
This:
actually tells PHP to call a method
Template::isAllowed()
, which obviously doesn't exist as given by your fatal error.You cannot treat
Template::isAllowed()
as if it were a real method by assigning a closure to a property. However you can still call the closure that is assigned to the$Template->isAllowed
property (which is an instance ofClosure
). To do that, you need to either assign the property to a variable then call that:Or use
call_user_func()
:简单来说,这是行不通的——您不能在 PHP 中动态添加类方法,就这样。这在将闭包定义为类中的方法之类的地方进行了讨论。
Simply this does not work -- you can not add class methods dynamically in PHP, period. This was discussed at places like define a closure as method from class.