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 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题