Skip to content
Tags

,

Multiple Inheritance

by João Pedro Pereira on July 18th, 2012

A very common problem PHP Developers find in Object Oriented Programming is the needs of Multiple Inheritance and PHP doesn’t support multiple inheritance, at least officially.

Fortunately, there are ways of doing this, without having to duplicate code.

Extension Manager

/**
* Multiple Inheritance
*
* Extension Manager
*
* @author Joao Pedro Pereira <contacto at joaopedropereira.com>
* @package blog <http: //joaopedropereira.com/blog/>
* @date 18.7.2012
*
*/
abstract class ExtensionManager
{
/**
* @var array
*/
protected $_extensions = array();

/**
* Stores a new Object in the $this->_extesions to be
* accessed after
*
* @param Object
*/
public function newExtension( $object )
{
$this->_extensions[] = $object;
}

/**
* Call dinamicaly the methods
*
* @param function
* @param mixed
*
* @return function execution
*
*/
public function __call( $method, $args )
{
foreach( $this->_extensions as $ext )
{
if( method_exists( $ext, $method ) ) {
return call_user_method_array( $method, $ext, $args );
}
}
throw new Exception('The Method: ', $method ,' does not exists!');
}
}

Extended Classes


class Ext1{
protected $name;
public function setName($name){
$this->name = $name;
}

public function getName(){
return $this->name;
}
}

class Ext2{
protected $country;
public function setCountry($country){
$this->country = $country;
}

public function getCountry(){
return $this->country;
}
}

Final Class


final class Base extends ExtensionManager
{
function __construct()
{
parent::newExtension( new Ext1() );
parent::newExtension( new Ext2() );
}

public function printTest()
{
return $this->getName().' is from: '.$this->getCountry();
}
}

How To Use It


$test = new Base();
$test->setName("Joao");
$test->setCountry("Portugal");
echo $test->printTest();

 

Please pay attention to the Diamond Problem when using multiple inheritance. This approach will use always the method from the first  extension.

From → PHP

One Comment
  1. A nice workaround for a problem secondary problem, being the first using deprecated languages.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS