3

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.

0

5 Answers 5

6

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

Sign up to request clarification or add additional context in comments.

Comments

5

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 https://www.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.

Comments

2

From the PHP Manual:

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

Comments

0

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

Comments

-2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.