Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating child classes from parent class (PHP)

Tags:

oop

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)

like image 829
Austin Hyde Avatar asked Jun 29 '09 19:06

Austin Hyde


1 Answers

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();
like image 109
Paul Dixon Avatar answered Sep 24 '22 08:09

Paul Dixon