douzhi3105 2012-02-27 09: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 14: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部