了解静态方法的php处理(非静态方法不能静态调用)
作者:互联网
<?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样式的构造函数,因为它共享类的相同名称.并且以静态方式调用类的构造函数会引发致命错误:
Non-static method X::x() cannot be called statically, assuming $this from incompatible context
实际上,对于所有非静态魔术方法都是如此,您可以在实现中看到: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;
}
标签:static-methods,php 来源: https://codeday.me/bug/20191122/2061449.html