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.
source share