douxian8883 2016-12-16 07:44
浏览 48
已采纳

为什么调用__call而不是__callStatic

I tried to refer this question on SO, but still don't get it.

<?php

class A {
    public function __call($method, $parameters) {
        echo "I'm the __call() magic method".PHP_EOL;
    }

    public static function __callStatic($method, $parameters) {
        echo "I'm the __callStatic() magic method".PHP_EOL;
    }
}

class B extends A {
    public function bar() {
        A::foo();
    }

    public function foo() {
        parent::foo();
    }
}

(new B)->bar();
(new B)->foo();

From what I understand, the bar function is calling the foo method on class A statically but the foo method call the method using the instance of A which is the parent of B. I am expecting it should gives me:

I'm the __callStatic() magic method
I'm the __call() magic method

But, apparently, I get:

I'm the __call() magic method
I'm the __call() magic method
  • 写回答

2条回答 默认 最新

  • douliang1900 2016-12-16 08:17
    关注

    From relevant issue:

    ...A::foo() is not necessarily a static call. Namely, if foo() is not static and there is a compatible context ($this exists and its class is either the class of the target method or a subclass of it), an instance call will be made.

    If foo() is static it works as you expect:

    class A {
        public function __call($method, $parameters) {
            echo "I'm the __call() magic method $method".PHP_EOL;
        }
    
        public static function __callStatic($method, $parameters) {
            echo "I'm the __callStatic() magic method $method".PHP_EOL;
        }
    }
    
    class B extends A {
        public static function foo() { // <-- static method
            parent::foo();
        }
    }
    
    (new B)->foo();
    

    I'm the __callStatic() magic method foo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了