Creating instances of child classes from the parent class (PHP)

I have a class with factory -pattern function in it:

abstract class ParentObj { public function __construct(){ ... } public static function factory(){ //returns new instance } } 

I need the children to be able to call the factory function and return an instance of the calling class: $child = Child::factory(); and preferably without overriding the factory function in the child class.

I tried several different ways to achieve this to no avail. I would rather stay away from solutions that use reflection, like __CLASS__ .

(I use PHP 5.2.5 if that matters)

+7
oop php
source share
2 answers

If you can upgrade to PHP 5.3 ( released June 30, 2009 ), check out the late static binding , which can provide a solution:

 abstract class ParentObj { public function __construct(){} public static function factory(){ //use php5.3 late static binding features: $class=get_called_class(); return new $class; } } class ChildObj extends ParentObj{ function foo(){ echo "Hello world\n"; } } $child=ChildObj::factory(); $child->foo(); 
+10
source share

In my humble opinion, what you are trying to do does not make sense.

Figure A factory will work as follows:

 abstract class Human {} class Child extends Human {} class Fool extends Human {} class HumanFactory { public static function get($token) { switch ($token) { case 'Kid' : return new Child(); case 'King': return new Fool(); default : throw new Exception('Not supported'); } } } $child = HumanFactory::get('Kid'); 
-one
source share

All Articles