加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 匿名函数/关闭并使用self ::或static ::

发布时间:2020-12-13 17:34:32 所属栏目:PHP教程 来源:网络整理
导读:我正在使用匿名函数,我在对象之外创建匿名函数,然后将其添加到稍后将使用__callStatic魔术函数的对象.正在添加的包含父类的方法的闭包.我想知道我是否能够从关闭中调用这些方法? 现在我得到这个错误: EmptyObject::addMethod('open',function(){ if (stati
我正在使用匿名函数,我在对象之外创建匿名函数,然后将其添加到稍后将使用__callStatic魔术函数的对象.正在添加的包含父类的方法的闭包.我想知道我是否能够从关闭中调用这些方法?

现在我得到这个错误:

EmptyObject::addMethod('open',function(){
    if (static::_hasAdapter(get_class(),__FUNCTION__))
            return self::_callAdapter(get_class(),__FUNCTION__,$details);

    echo '<p>You have mail!</p>';
});

抛出这个错误:

Fatal error: Cannot access static:: when no class scope is active in

//Add the functions
EmptyObject::addMethod('open',function(){
    if (EmptyObject::_hasAdapter('EmptyObject',__FUNCTION__))
            return EmptyObject::_callAdapter('EmptyObject',$details);

    echo '<p>You have mail!</p>';
});

抛出此错误是因为该方法受到保护

Fatal error: Uncaught exception ‘BadMethodCallException’ with message ‘Method ‘_hasAdapter’ was not found in class EmptyObject’

您可以使用 Closure::bind()(PHP> = 5.4.0)
abstract class EmptyObject
{
   protected static $methods = array();

   final public static function __callStatic($name,$arguments)
   {
      return call_user_func(self::$methods[$name],$arguments);
   }

   final public static function addMethod($name,$fn)
   {
      self::$methods[$name] = Closure::bind($fn,NULL,__CLASS__);
   }

   final protected static function protectedMethod()
   {
      echo __METHOD__ . " was called" . PHP_EOL;
   }
}

现在传递给EmptyObject :: addMethod()的任何匿名函数都将在EmptyObject类的范围内运行

EmptyObject::addMethod("test",function()
{
   self::protectedMethod();
});


// will output:
// EmptyObject::protectedMethod was called

EmptyObject::test();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读