PHP Multiple Inheritance

PHP 5 jest bardzo rozbudowanym językiem, zapewnia nam większość dobrodziejstw programowania obiektowego, ale nie wszystkie. Kiedyś zdarzyło się, że zabrakło mi wielokrotnego dziedziczenia. Niby wszystko da się obejść, np dziedzicząc piętrowo, ale bywa to mało wygodne.

Z potrzeby chwili powstała proteza pozwalająca na zasymulowanie wielokrotnego dziedziczenia.

Poniżej kod i przykład wykorzystania.


class Inheritance
{
var $__classes=array();
var $__data=array();

function __construct()
{
}
function __set($key,$value)
{
$backtrace = debug_backtrace();
$obj = $backtrace[2]['object'];

if(!isset($obj->$key))
{
$obj->__set_backtraced($key,$value);
}
else
{
$obj->$key = $value;
}

return $value;
}
function __set_backtraced($key,$value)
{
return $this->__data[$key] = $value;
}
function __get($key)
{
if(isset($this->__data[$key]))
{
$value = $this->__data[$key];
}
else
{
$backtrace = debug_backtrace();
$obj = $backtrace[3]['object'];

if(!isset($obj->$key))
{
$value = $obj->__get_backtraced($key);
}
else
{
$value = $obj->$key;
}
}

return $value;
}
function __get_backtraced($key)
{
return $this->__data[$key];
}
function __inherit($class)
{
if(is_object($class))
{
$this->__classes[] = $class;
}
else
{
$this->__classes[] = new $class();
}
}
function __call($method,$args)
{
$found = false;
foreach($this->__classes as $obj)
{
if (method_exists($obj, $method))
{
$found = $obj;
}
}
if (!$found)
{
throw new Exception("unknown method [$method]");
}
return call_user_func_array(array($found, $method),$args);
}
}


class A extends Inheritance
{
function __construct()
{
$this->__inherit('B');
$this->__inherit(new C('I Am Weasel'));
}
}


class B extends Inheritance
{
function print_b($string)
{
echo "B sayz: $string
";
}
}


class C extends Inheritance
{
function __construct($string)
{
$this->str = $string;
}
function print_c($string)
{
echo "C sayz: ".$this->str." (instead of: ".$string.")
";
}
}


$a=new A();
$a->print_b("It's alive!");
$a->print_c("I. R. Baboon");