PHP static factory method: dynamic instance of the calling class

This PHP question is related to this question , but a little different. I have a static factory method called create() that creates an instance of the class. I want the method to dynamically create an instance of the class (under) on which it is called. Thus, the class that it creates must be defined at runtime. But I want to do this without having to redefine the static factory method in the subclass (and that would be perfectly correct in my example, since the subclass has no new data elements to initialize). Is it possible?

 class Foo { private $name; public static function create($name) { //HERE INSTED OF: return new Foo($name); //I WANT SOMETHING LIKE: //return new get_class($this)($name);//doesn't work //return self($this);//doesn't work either } private function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } // the following class has no private data, just extra methods: class SubFoo extends Foo { public function getHelloName() { echo "Hello, ", $this->getName(), ".\n"; } } $foo = Foo::create("Joe"); echo $foo->getName(), "\n"; // MUST OUTPUT: Joe $subFoo = SubFoo::create("Joe"); echo $subFoo->getHelloName(), "\n"; // MUST OUTPUT: Hello, Joe. 
+5
source share
3 answers

You must create an object using the Late Static Binding method get_called_class() . The second option is to use the static .

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 the conclusion:

 Joe Hello, Joe 
+6
source

return new static();

the static keyword is already reserved

+4
source

Yes, possibly with late static binding to 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 it

 echo parent::getName(); echo self::getHelloName(); 
-3
source

Source: https://habr.com/ru/post/1213421/


All Articles