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.

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

报告相同问题?