Austin Hyde
Austin Hyde

Reputation: 27436

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)

Upvotes: 8

Views: 9374

Answers (2)

Paul Dixon
Paul Dixon

Reputation: 300835

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();

Upvotes: 12

Philippe Gerber
Philippe Gerber

Reputation: 17836

In my humble opinion what you're trying to do makes no sense.

A factory pattern would work like this:

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');

Upvotes: 0

Related Questions