【问题标题】:The mysterious behaviour of __callStatic method__callStatic 方法的神秘行为
【发布时间】:2013-01-22 21:01:37
【问题描述】:

所以问题 Weird behaviour with triggering __callStatic() from non-static method 很好,因为它解释了 __callStatic 没有从类本身调用的奇怪行为(请注意,我在 5.3.3 中没有看到这种行为,但在 5.3.8 和 5.3.12 )。似乎 __callStatic 只能从类外部调用。现在这是事实。但是,如果我真的希望在我的班级中调用 __callStatic,我该怎么办?我应该使用什么语法来解决这个问题?

【问题讨论】:

  • 你能包含一个测试用例吗?

标签: php


【解决方案1】:

它不必来自类外部,而不必来自对象上下文(即$this 是类的一个实例)。所以你可以把这个调用包装在一个静态方法中,例如:

class TestCallStatic
{
    public function __call($func, $args)
    {
        echo "__call($func)";
    }

    public static function __callStatic($func, $args)
    {
        echo "__callStatic($func)";
    }

    public function test()
    {
        self::_test();
    }
    protected static function _test()
    {
        self::i_am_static();
    }
}

$test = new TestCallStatic();
$test->test();

输出:

__callStatic(i_am_static)

【讨论】:

  • 这就是解决方案。是为了理解你要调用静态函数的php解释器。通过使用辅助静态函数 _test 可以避免模棱两可的调用。我的代码中唯一的区别是需要使用 $this 所以: self::_test($this);和静态函数 _test($myClassInstance)
  • 我会尝试将需要$this 的部分与不需要的部分分开(仅将“静态”部分移动到_test) - 如果您的班级可以这样做。它使封装更容易,代码看起来更干净。
  • 在 5.3.3、5.3.8 和 5.3.12 上测试成功
【解决方案2】:

您可以将功能抽象为另一个方法,例如 Class::magicCall($method, $args),然后在 __callStatic() 中调用它。这样,您也可以通过直接调用 Class::magicCall() 来访问该功能。

【讨论】: