Access of Non-Static Function of a Class in PHP

2020-02-14 07:45发布

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.

标签: php oop class
5条回答
霸刀☆藐视天下
2楼-- · 2020-02-14 07:58

From the PHP Manual:

Calling non-static methods statically generates an E_STRICT level warning.

查看更多
仙女界的扛把子
3楼-- · 2020-02-14 07:59

I don't believe that you can access a method of a class with out a instance of the object.

查看更多
够拽才男人
4楼-- · 2020-02-14 08:01

This works because you have not enabled the E_STRICT error level. Once enabled PHP will stop letting you to do this.

查看更多
欢心
5楼-- · 2020-02-14 08:09

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.

查看更多
Juvenile、少年°
6楼-- · 2020-02-14 08:14

It's legal, but generally frowned upon, until you reference $this in your statically called method which will throw a fatal error.

查看更多
登录 后发表回答