문제

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