Static methods in PHP: what for?

2019-06-05 00:48发布

问题:

I'm terribly sorry for asking such a silly question, but I'm new to OOP and trying to figure out what static methods are used for. Here's an example PHP code:

class foo{
static function bar(){
//do something here
}
public function baz(){
//do something different
}
}

Documentation says:

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class

However, the both methods from the example above can be accessed from outside of the class with like:

foo::bar();
foo::baz();

It works (at least for PHP 5.3 that I'm using) without instantiation of the class foo. So, what's the point of using static methods, if the both ways work??

Forgive me once again for such a noob question. I've been really trying hard to find it out myself with no success. Thanks.

回答1:

Static methods are globally available tools (helpers) and are often overused. Static methods are death to testability and should be avoided almost completely.

Their advantage as well as disadvantage is that they live in the global scope, you can call them from anywhere, which makes them code smells in most cases because they break encapsulation.

On language level, as Kolink mentions, things like mysqli:real_escape_string() make sense of course, but on application level, you usually don't want to pollute your global scope and break encapsulation like that. You'd rather think of what tools you really need and where and inject them bundled into meaningful groups (classes).

Your foo::baz() raises a warning in strict mode (which should always be on):

Strict standards: Non-static method foo:baz() should not be called statically in yourfile.php on line x



回答2:

Generally they can be used for "helper" functions, such as mysqli::real_escape_string(), where the function is relevant to the class but not locked to any specific instance of it.



标签: php oop static