Austin Hyde Austin Hyde - 5 months ago 18
PHP Question

Instantiating child classes from parent class (PHP)

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

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


I need 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 have tried multiple different ways of achieving this to no avail. I would prefer to stay away from solutions that use reflection, like
__CLASS__
.

(I am using PHP 5.2.5 if it matters)

Answer

If you can upgrade to PHP 5.3 (released 30-Jun-2009), check out late static binding, which could 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();