Multiple Inheritance

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

[sourcecode language=”php”]
/**
* Multiple Inheritance
*
* Extension Manager
*
* @author Joao Pedro Pereira
* @package 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!’);
}
}
[/sourcecode]

Extended Classes

[sourcecode language=”php”]

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;
}
}

[/sourcecode]

Final Class

[sourcecode language=”php”]

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();
}
}

[/sourcecode]

How To Use It

[sourcecode language=”php”]

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

[/sourcecode]

 

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

1 comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.