简体   繁体   中英

PHP: Abstract Static Function Best Practice

So you can't make an abstract static function in php.

The alternatives as I see them are to:

  1. Make the function non-static and write extra boilerplate code to create and store the object so I can access that function.

     abstract class Foo { abstract public function bar(); } abstract class Good { public function bar() { ... } } // boilerplate to access Good->bar()... potentially a lot in multiple files $g = new Good(); $g->bar(); 
  2. Fill in the static function in my abstract class with a BadMethodCallException , so that any call to a child class which doesn't implement it will throw the exception.

     abstract class Foo { public static function bar() { throw new BadMethodCallException("Not Implemented By Child Class :("); } } class Good extends Foo { public static function bar() { // ... } } class Bad extends Foo { // no bar implementation } Good::bar(); // works Bad::bar(): // exception 

I'm leaning towards 2. but was wondering if there's any community consensus on this issue or best practices.

I ended up making an interface with a static function, then implementing the interface in the abstract class. This forces the child classes to define the method, which is basically what I wanted with an abstract static function.

interface ModelFactoryInterface {
  public static function offer();
}

abstract class ModelHelper implements ModelFactoryInterface {

  protected $tester;

  public function __construct($tester) {
    $this->tester = $tester;
  }

}

/* Location
 * ------------------------------------------------------ */
final class LocationHelper extends ModelHelper {

  public static function offer() {
    return new Location(...)
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM