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条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?