如果您尝试运行下面的代码并查看回溯输出,您将看到 PHP 在静态上下文中调用时将 instanceFunc() 转换为静态方法。但是,在实例上下文中,它会将其视为实例调用。
如果您在混合中引入实例变量(删除注释掉的行),那么从静态调用调用 instanceFunc() 时会遇到致命错误。
这意味着 PHP 允许从静态上下文中调用所有本质上是静态的方法(不使用实例变量),但一旦该合约被破坏,就会产生错误。因此,使用静态函数似乎只是与其他面向对象语言保持一致的好习惯。
关于 staticFunc() 两个调用都表明 PHP 将它们解释为静态调用,这是意料之中的。
class A {
private $x = 5;
private $y = 6;
private $z;
public function instanceFunc() {
//$this->z = $this->y * $this->x;
//echo $this->z;
var_dump(reset(debug_backtrace()));
}
public static function staticFunc() {
var_dump(reset(debug_backtrace()));
}
}
$a = new A();
A::instanceFunc(); // static call of intended instance method
$a->instanceFunc(); // instance call of instance method
A::staticFunc();
$a->staticFunc();
示例输出(使用注释运行的代码):
array(6) { ["file"]=> string(59) "test.php" ["line"]=> int(19) ["function"]=> string(12) "instanceFunc" ["class"]=> string(1) "A" ["type"]=> string(2) "::" ["args"]=> array(0) { } }
array(7) { ["file"]=> string(59) "test.php" ["line"]=> int(22) ["function"]=> string(12) "instanceFunc" ["class"]=> string(1) "A" ["object"]=> object(A)#8 (3) { ["x:private"]=> int(5) ["y:private"]=> int(6) ["z:private"]=> NULL } ["type"]=> string(2) "->" ["args"]=> array(0) { } }
array(6) { ["file"]=> string(59) "test.php" ["line"]=> int(24) ["function"]=> string(10) "staticFunc" ["class"]=> string(1) "A" ["type"]=> string(2) "::" ["args"]=> array(0) { } }
array(6) { ["file"]=> string(59) "test.php" ["line"]=> int(26) ["function"]=> string(10) "staticFunc" ["class"]=> string(1) "A" ["type"]=> string(2) "::" ["args"]=> array(0) { } }