Revisiting multiple inheritance in PHP

published Mar 18, 2006, last modified Jun 26, 2013

The updated technique for simulation of multiple inheritance in PHP

As it turns out, version 0.7 of the runkit extension for PHP has problems when copying methods from a class into another. Of course, this punts my original multiple inheritance simulation technique. The bug in detail: copying of methods from "parent" classes into the "child" class succeeds, but later on, when attempting to use a method, PHP requests ludicrous amounts of memory to the OS, which causes PHP to fail.

In lieu of that problem, I decided to explore alternatives. The final, usable alternative seems to be:

function inherits_from($destClassName,$srcClassNameList) {
    foreach ($srcClassNameList as $s) {
        runkit_class_adopt($destClassName,$s);
    }
}

And this version does work without the memory exhaustion problem. In short:

inherits_from(
        'MultipleInheritedClass',
        array('A','B','C')
        );
?>

The inherits_from construct does the magic. All you need to type there is:

  • The name of the "child" class
  • An array containing the names of the "parent" classes

Of course, this technique works only in PHP 5, with the runkit extension.

Despite the cutting-edge requirements, I've just shown there's a practical way to build multiple inheritance in PHP. Mixin classes, aggregate classes, they're a few keystrokes away. Long live PHP!

Oh, by the way, did I mention that I built convenient RPM packages of runkit?