dscss8996 2018-06-20 05:07
浏览 103
已采纳

为什么我们通过箭头符号' - >'从那个子对象调用Yii2静态组件方法?

In normal way, I know that we can call parent static method with :: sign but it seems that in Yii2 Framework, we should call static components method via arrow sign (object operator).

I'd like to know how its possible?

For example, in

$foo->on(Foo::EVENT_HELLO, 'function_name');

on() is an static method of yii\base\component but we call it with arrow.

  • 写回答

1条回答 默认 最新

  • doushun9875 2018-06-20 07:41
    关注

    Component::on() is not static:

    public function on($name, $handler, $data = null, $append = true)
    {
        $this->ensureBehaviors();
        if (strpos($name, '*') !== false) {
            if ($append || empty($this->_eventWildcards[$name])) {
                $this->_eventWildcards[$name][] = [$handler, $data];
            } else {
                array_unshift($this->_eventWildcards[$name], [$handler, $data]);
            }
            return;
        }
        if ($append || empty($this->_events[$name])) {
            $this->_events[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_events[$name], [$handler, $data]);
        }
    }
    

    https://github.com/yiisoft/yii2/blob/bc9a82ff80e0abc3ce1430310d2b9b1f70f18c62/framework/base/Component.php#L514

    Event::on() is static:

    public static function on($class, $name, $handler, $data = null, $append = true)
    {
        $class = ltrim($class, '\\');
        if (strpos($class, '*') !== false || strpos($name, '*') !== false) {
            if ($append || empty(self::$_eventWildcards[$name][$class])) {
                self::$_eventWildcards[$name][$class][] = [$handler, $data];
            } else {
                array_unshift(self::$_eventWildcards[$name][$class], [$handler, $data]);
            }
            return;
        }
        if ($append || empty(self::$_events[$name][$class])) {
            self::$_events[$name][$class][] = [$handler, $data];
        } else {
            array_unshift(self::$_events[$name][$class], [$handler, $data]);
        }
    }
    

    https://github.com/yiisoft/yii2/blob/bc9a82ff80e0abc3ce1430310d2b9b1f70f18c62/framework/base/Event.php#L103

    But I've never seen that someone is using it in non-static way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?