Simulating multiple inheritance in PHP 5 via the runkit extension

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

How to simulate multiple inheritance in PHP using the runkit extension

Update: there's a serious bug with this approach and `runkit` 0.7. For an updated approach, try Revisiting multiple inheritance in PHP. Oh, there are RPM packages for runkit here.

Here's some code that will help you simulate multiple inheritance in PHP 5 with maximum portability. This requires the runkit extension for PHP, regrettably. Hope runkit gets rolled into baseline PHP 5.

This code also emulates the aggregate_methods function from the Object aggregation functions in PHP 4.

Say you have:

We can generalize the runkit_method_copy to work with all classes:

Now, the function call will work for all classes without modification (honorable exception made of classes whose method namespaces clash). This little bit of magic lets you 'inherit' from multiple classes, taking full advantage of methods defined in other classes (such as classes written explicitly to work as mix-ins). Most of the introspection machinery won't exactly work, but those are the breaks.

In practical terms:

So there you go: there is multiple inheritance available in PHP!