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();
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top