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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀