Inheritance of static members in PHP

后端 未结 3 1476
走了就别回头了
走了就别回头了 2020-12-02 18:25

In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class. But I\'m wondering if there\'s any way around this.

I\'m try

3条回答
  •  无人及你
    2020-12-02 19:12

    Classic example of why using statics as globals (functions in this case) is a bad idea no matter the language.

    The most robust method is to create multiple implementation sub classes of an abstract base "Action" class.

    Then to try and remove some of the annoyance of instantiating an instance of the class just to call it's methods, you can wrap it in a factory of some sort.

    For example:

    abstract class AbstractAction {
      public abstract function do();
    }
    
    class FooAction extends AbstractAction {
      public function do() {
        echo "Do Foo Action";
      }
    }
    
    class BarAction extends AbstractAction {
      public function do() {
        echo "Do Bar Action";
      }
    }
    

    Then create a factory to "aid" in instantiation of the function

    class ActionFactory {
      public static function get($action_name) {
        //... return AbstractAction instance here
      }  
    }
    

    Then use it as:

    ActionFactory::get('foo')->do();
    

提交回复
热议问题