title: PHP static factory method: dynamically instantiate instance of the calling class
body: <p>This PHP question is related to <a href="https://stackoverflow.com/questions/28401274/version-of-class-that-binds-at-run-time-rather-than-at-compile-time">this question</a>, but is a bit different. I have a static factory method called <code>create()</code> which instantiates a class instance. I want the method to dynamically instantiate an instance of the (sub)class on which it is called. So, the class it instantiates must be determined at runtime. But I want to do this without having to redefine the static factory method in the subclass (and this would be perfectly valid in my example since the subclass has no new data members to initialize). Is this at all possible?</p>
  
  <pre><code>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-&gt;name = $name;
  
    }
  
    public function getName() {
  
      return $this-&gt;name;
  
    }
  
  }
  
  // the following class has no private data, just extra methods:
  
  class SubFoo extends Foo {
  
    public function getHelloName() {
  
      echo "Hello, ", $this-&gt;getName(), ".\n";
  
    }
  
  }
  
  
  $foo = Foo::create("Joe");
  echo $foo-&gt;getName(), "\n"; // MUST OUTPUT: Joe
  
  $subFoo = SubFoo::create("Joe");
  echo $subFoo-&gt;getHelloName(), "\n"; // MUST OUTPUT: Hello, Joe.
  </code></pre>