PHP: call child constructor from static method in parent

I want to have a static method in the parent class that instantiates any subclass I call this method on.

An example to make this clearer:

 class parent {
     public static method make_objects ($ conditions) {
         for (...) {
             // here i want to create an instance
             // of whatever subclass i am calling make_objects on
             // based on certain $ conditions
         }
     }
 }

 class sub extends parent {
     ...
 }

 $ objects = sub :: make_objects ($ some_conditions);
+7
constructor php static subclass
source share
4 answers

As in php 5.3, you can use static to do this

<?php class 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

 <?php class 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=A t=B B::__construct type of o=B t=C C::__construct type of o=C 
+8
source share

I think you need 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 such an instance:

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

or

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

But why do you want all subclasses to extend the parent? Don't you need to have a parent for your models (subclasses), and then a factory class that creates instances for these models depending on the given conditions?

+1
source share

Umm, right:

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

make the parent class an abstract class and make the parent method also abstract

 abstract static class parent { abstract function make_method() { // your process } } class child extends parent { public function __construct() { parent::make_method(); } } 
-one
source share

All Articles