title: How to assign ancestor to descendant type in PHP - class type casting
body: <p>I am trying to assign an ancestor(A) to descendant(B) type variable and call descendant method on ancestor in PHP but I can't get it working.</p>
  
  <pre><code>class B extends A{
     public function c(){ echo 'B.c'}
  }
  </code></pre>
  
  <p>I have tried:</p>
  
  <ol>
  <li><p>Rewriting <code>B</code> constructor</p>
  
  <pre><code>class B extends A{
      public function __construct($parent)
      {
          $this = $parent;
      }
      ...
  }
  </code></pre></li>
  </ol>
  
  <p><code>$this</code> cannot be rewritten, so it's a no-go.</p>
  
  <ol start="2">
  <li><p>This thing I am forgetting how is it called</p>
  
  <pre><code>function d(B $b){ 
      $b = new A(); 
      b.c();
  }
  </code></pre></li>
  <li><p>Explicit type casting</p>
  
  <pre><code>function d(){
      $b = (B) new A();
      b.c();
  }
  </code></pre>
  
  <p>Or </p>
  
  <pre><code>function d(){ 
      $b = settype(new A(),'B');
      b.c()
  }
  </code></pre></li>
  </ol>
  
  <p>This doesn't work either as <code>settype</code> only allows certain types not other user defined object types.</p>