PHP: call child constructor from static method in parent PHP: call child constructor from static method in parent php php

PHP: call child constructor from static method in parent


As of php 5.3 you can use the static keyword for this

<?phpclass A {  public static function newInstance() {    $rv = new static();      return $rv;  }}class B extends A { }class C extends B { }$o = A::newInstance(); var_dump($o);$o = B::newInstance(); var_dump($o);$o = C::newInstance(); var_dump($o);

prints

object(A)#1 (0) {}object(B)#2 (0) {}object(C)#1 (0) {}

edit: another (similar) example

<?phpclass A {  public static function newInstance() {    $rv = new static();      return $rv;  }  public function __construct() { echo " A::__construct\n"; }}class B extends A {  public function __construct() { echo " B::__construct\n"; }}class C extends B {  public function __construct() { echo " C::__construct\n"; }   }$types = array('A', 'B', 'C');foreach( $types as $t ) {  echo 't=', $t, "\n";  $o = $t::newInstance();  echo '  type of o=', get_class($o), "\n";}

prints

t=A A::__construct  type of o=At=B B::__construct  type of o=Bt=C C::__construct  type of o=C


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?


Umm, wouldn't that be:

class sub extends parent {  public static function make_objects($conditions) {    //sub specific stuff here    //....  }}