如果您尝试运行下面的代码,并期待在回溯输出,你会看到PHP转换instanceFunc ()在静态上下文中调用时使用静态方法。但是,在实例上下文中,它会将其视为实例调用。
如果您将实例变量引入mix(删除注释掉的行),那么当从静态调用调用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) { } }
测试你的代码让我哭了... – Shoe 2011-04-19 17:18:46
套用伊恩·马尔科姆:“仅仅因为你可以并不意味着你应该” :)的 – 2011-04-19 17:38:19
可能重复[是否在PHP的静态方法与非静态方法有什么区别?(http://stackoverflow.com/questions/2439036/does-static-method-in-php-have-any-difference -with-非静态方法) – danorton 2014-03-25 18:58:38