了解静态方法的 PHP 处理(非静态方法不能静态调用)


understanding php handling of static methods (non-static method cannot be called statically)

<?php
class T {
        public function x(){
                return true;
        }    
}
var_dump(T::x());
class X {
        public function x(){
                return true;
        }
}    
var_dump(X::x());

此代码导致:

bool(true)
PHP Fatal error:  Non-static method X::x() cannot be called statically in test.php on line 16

为什么 T::x(( 工作(当它应该失败时(而 X::x(( 失败(它应该失败(?

X::x()实际上是一个PHP4风格的构造函数,因为它共享相同的类名称。以静态方式调用类的构造函数会引发致命错误:

非静态方法 X::x(( 不能静态调用,假设$this来自不兼容的上下文

实际上,所有非静态魔术方法都是这种情况,正如您在实现中看到的那样:http://lxr.php.net/xref/PHP_5_5/Zend/zend_compile.c#1636

唯一可能被隐式静态调用(并引发E_STRICT(的情况是当函数没有特殊处理时:

if (some large if/else's for the magic methods) {
    // flag isn't set…
} else {
    CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC;
}