douzhi3105 2012-02-27 17:24
浏览 90
已采纳

从非静态方法触发__callStatic()的奇怪行为

I found this weird behaviour with PHP classes (v5.3.8).

You have:

class foo {
  function __call($func, $args) {
    if ($func == 'bar')
      echo "non-static __call";
  }

  static function __callStatic($func, $args) {
    if ($func == 'bar')
      echo "__callStatic";
  }

  function callMe() {
    self::bar();
  }
}

Then you do:

foo::bar() // outputs '__callStatic' as expected.
$f = new foo;
$f->callMe(); // outputs 'non-static __call', as I did not expect.

You see, a non-existent static method called from a non-static function triggers __call() instead of __callStatic(). I was wondering if this is supposed to work like this or is this some kind of bug?

[EDIT]

I forgot to try static::bar(); on callMe() but no, it didn't work either.

I (think I) understand inhan's comment but still... if I'm calling the class itself, not the instance or object, immediate logic for me says it should trigger __callStatic(). Oh well.

Thank you for your answers/comments.

  • 写回答

2条回答 默认 最新

  • douaoli5328 2012-02-27 22:38
    关注

    You might be confused by what these things mean from within the context of a class method:

    class B extends A {
      public function test() {
        A::foo();
        self::foo();
        static::foo();
      }
    }
    

    None of those mean "call the static method named foo." It simply means "call the method named foo" at the place in the inheritance tree as specified by what is left of the colons.

    Normally, without magic, you only have one function named foo, so the meaning is straightforward. However, when you overload with both magic methods, the call is ambiguous. PHP defaults to using __call() before __callStatic().

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

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作