PHP: call child constructor from static method in parent

前端 未结 4 1824
天命终不由人
天命终不由人 2021-01-17 17:45

I want to have a static method in a parent class that creates instances of whatever subclass i call this method on.

An example to make this more clear:

cl         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 18:10

    I think you want something like this:

    class parent {
      public static function make_object($conditionns) {
        if($conditions == "case1") {
          return new sub();
        }
      }
    }
    
    class sub extends parent {
    
    }
    

    Now you can create an instance like this:

    $instance = parent::make_object("case1");
    

    or

    $instance = sub::make_object("case1");
    

    But why would you want all the sub classes to extend the parent? Shouldn't you much rather have a parent for your models (sub classes) and then a factory class, that creates the instances for this models depending on the conditions given?

提交回复
热议问题