title: How to return subclass from constructor in PHP
body: <pre class="lang-php prettyprint-override"><code>&lt;?php
  
  class Super {
      public $my;
      public function __construct ( $someArg ) {
          if ( class_exists('Sub') ) {    // or some other condition
              return new Sub( $someArg );
          }
          $this-&gt;my = $someArg;
      }
  }
  
  class Sub extends Super {}
  
  ?&gt;
  </code></pre>
  
  <p>This doesn't work, as <code>new Super()</code> will be an "empty" <code>Super</code> object (all members are <code>NULL</code>). (PHP doesn't allow assignments to <code>$this</code>, so <code>$this = new Sub()</code> doesn't work either).</p>
  
  <p>I know the correct pattern would be a factory here. But that would require a lot of changes in the code, so I'm wondering whether it's possible to do it this way. Since <code>Sub</code> is-a <code>Super</code>, I don't see why it shouldn't be restricted from an OOP point of view.</p>