Calling a static method non statically

2019-08-19 08:14发布

问题:

I came across something like this, and am not sure what to make off it. Is there any good reason to do this, or to avoid it?

class Foo {

  static public function bar() {}

}

someMethod() {

  $instanceOfFoo->bar();

}

回答1:

The PHP documentation says:

[...] A property declared as static can not be accessed with an instantiated class object (though a static method can). [...] Static properties cannot be accessed through the object using the arrow operator ->.

without specifying anything special for static methods being called by ->. You should definitely avoid it though, because it causes confusion to the reader who's expecting $obj->meth() to be a non-static method and Cls::meth() a static method.

Surprisingly this behavior is not triggering any error. The reason for this is that a static method, called by $object->method() is internally translated to className::method() at run time (with the only difference being that $this = NULL is set).



回答2:

You can call the particular function as below.

Foo::bar();

You don't have to create an object to call a static function. Basically we write static functions to call the function without an instance of the class in which it's defined.

It's okay to call a static function with an object but why do so when you have a simpler and cleaner method.



标签: php static