PHP static factory method: dynamically instantiate instance of the calling class PHP static factory method: dynamically instantiate instance of the calling class php php

PHP static factory method: dynamically instantiate instance of the calling class


You must create object using Late Static Binding - method get_called_class() is useful. Second option is use static keyword.

Example:

class Foo {    private $name;    public static function create($name)     {        $object = get_called_class();        return new $object($name);    }    private function __construct($name)     {        $this->name = $name;    }    public function getName()     {        return $this->name;    }}class SubFoo extends Foo {    public function getHelloName()     {        return "Hello, ". $this->getName();    }}$foo = Foo::create("Joe");echo $foo->getName(), "\n";$subFoo = SubFoo::create("Joe");echo $subFoo->getHelloName(), "\n";

And output:

JoeHello, Joe


return new static();

there is already reserved keyword static


Yes, It is possible with late static binding feature of php.

Instead of

$foo = Foo::create("Joe");echo $foo->getName(), "\n"; // MUST OUTPUT: Joe$subFoo = SubFoo::create("Joe");echo $foo->getHelloName(), "\n"; // MUST OUTPUT: Hello, Joe.

try this

echo parent::getName();echo self::getHelloName();