在PHP中访问类的非静态函数 [英] Access of Non-Static Function of a Class in PHP
问题描述
为什么这在PHP中合法?
<?php
class Foo {
public function test(){
echohello\\ \\ n;
}
}
Foo :: test();
?>
test()是一个非静态函数,但我可以在没有实例的情况下访问它。
我相信这是因为向后兼容性。在PHP4中,你没有方法的static关键字(仍然寻找引用,但到目前为止,这是我发现的所有 http://us2.php.net/manual/en/language.oop5.static.php )。这样,PHP4代码仍然可以运行没有问题。
更好的做法是声明你的静态函数,如果你打开E_STRICT,你会看到一个通知关于此。
error_reporting(E_ALL | E_STRICT);
更新:这是我发现的最好的 http://bugs.php.net/bug.php?id=34990 和 http://bugs.php.net/bug.php?id=47891 。 / p>
Why is this legal in PHP?
<?php
class Foo {
public function test() {
echo "hello\n";
}
}
Foo::test();
?>
test() is a non-static function but I can access it without an instance.
I believe it's because of backwards compatibility. In PHP4 you didn't have the static keyword for methods (still looking for reference, but so far this is all I've found http://us2.php.net/manual/en/language.oop5.static.php). This way, PHP4 code can still run without a problem.
It is better practice to declare your static functions as such and if you turn on E_STRICT you'll see a notice about this.
error_reporting(E_ALL | E_STRICT);
Update: well, this is the best I've found http://bugs.php.net/bug.php?id=34990 and http://bugs.php.net/bug.php?id=47891.
这篇关于在PHP中访问类的非静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!