Revisiting 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:

<?php

class A { ...A's methods here... }

class B { ...B's methods here... }

class C { ...C's methods here... }

class MultipleInheritedClass { ...this class' methods here... } 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?

One Response to “Revisiting multiple inheritance in PHP”

  1. Romke van der Meulen Says:

    runkit_class_adopt fails if the childClass already inherits via the extends keyword.

Leave a Reply