PHP: multiple class inheritance

In PHP the extends keyword accepts only one class name after it, thus implying that multiple inheritance is not natively supported. However, sometimes it's preferable to have a class that inherits from different classes. To accomplish this task we need to use the __construct() method attached to any PHP class. Suppose that we have three classes, A, B, C where only the C class inherits directly from B:

class A 
{

  public $foo;
  protected $bar;
  private $baz;
  
  public function __construct()
  {
  
  
    $this->foo = 'Foo';
    $this->bar = 'Bar';
    $this->baz = 'Baz';
  
  
  }
  
  public function __get($property)
  
  {
  
    return $this->$property;
  
  
  }



}

class B 
{


  public $a = 'Lorem';
  protected $b = 'Ipsum';
  private $c = 'Dolor';
  
  
  public function __get($prop)
  
  {

    return $this->$prop;

  }


}

class C extends B 
{


}

Now C inherits from B, but not from A. To fix this problem, we can call the A's constructor within the B's constructor:

class C extends B 
{

  public function __construct() 
  
  {
  
    A::__construct();
  
  
  }


}

Now C is linked to A. We can create a method within the last class to test everything out:

class C extends B 
{

  public function __construct() 
  
  {
  
    A::__construct();
  
  
  }
  
  public function display()
  {
  
    $propArray = array($this->foo, $this->bar, $this->baz, $this->a, $this->b, $this->c);
    $html = '';
    
    foreach($propArray as $prop) {
    
      $html .= '<p>' . $prop . '</p>' . "\n";
    
    
    
    }
    
    return $html;
  
  }

}

A simple test:

$c = new C();
echo $c->display();

And here's the result:

This solution works fine as long as you define your properties within the constructor of the first class.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.