Question

Given the following code I am looking for pro's and con's of calling $this->myStaticFunc(); vs self::myStaticFunc();

class MyClass

  private function myPrivateFunc() {
    ...
    $this->myStaticFunc(); // or self::myStaticFunc();
    ...
  }

  // no need to tell me that i can't use $this in here
  public static function myStaticFunc() { ... }

}

// access static function
MyClass::myStaticFunc();
Was it helpful?

Solution

The cons of using $this->myStaticFunction() are:

  • It doesn't clearly indicate what you intend (-> indicates you are doing something with an object, but you aren't),
  • It may wind up calling something you didn't expect,
  • It will likely confuse the reader (all the reader will be able to determine for sure is that the author doesn't understand basic OO principles),
  • And it's simply wrong: static functions belong to classes, not objects. Call them through a class (including self), not an object.

The only possible pro is that you may want to override the static function in a child class, but this indicates that the function belongs to the object and not the class. In that case it would be more appropriate to use an instance method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top