1

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();

}
Jeroen De Dauw
  • 10,321
  • 15
  • 56
  • 79
  • If this was another language it would probably throw an error. I imagine that either it was written by a beginner who forgot about it being declared static or by an expert who is taking advantage of the fact by doing different things depending on the context. I would strongly recommend refactoring it into two methods, one static and the other not. – Waleed Khan Apr 02 '13 at 04:23
  • throw some more light on your question. – xkeshav Apr 02 '13 at 04:26
  • possible duplicate of [Calling static method non-statically](http://stackoverflow.com/questions/15707029/calling-static-method-non-statically) – Ejaz May 06 '15 at 11:46
  • @WaleedKhan No, it's perfectly valid, in C#, it's even suggested to mark methods static if they don't use any object's member so that it can be used in both ways. The opposite is, however, absolutely true, non static method should never ever be called statically! – Patrick Allaert Aug 30 '17 at 15:55

2 Answers2

5

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).

Shoe
  • 74,840
  • 36
  • 166
  • 272
0

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.

Techie
  • 44,706
  • 42
  • 157
  • 243
  • I think the question asks what to think of code that calls a static method through an instance, not how to call a static method. In fact I think the poster is well-aware of traditional usage of static members. – Waleed Khan Apr 02 '13 at 04:20
  • 1
    I have given him my perspective telling that what he has written is not required. – Techie Apr 02 '13 at 04:23