Can I extend a class using more than 1 class in PHP?


If I have several classes with functions that I need but want to store separately for organisation, can I extend a class to have both?

i.e. class a extends b extends c

edit: I know how to extend classes one at a time, but I'm looking for a method to instantly extend a class using multiple base classes - AFAIK you can't do this in PHP but there should be ways around it without resorting to class c extends b, class b extends a

7/9/2012 5:59:02 PM

Accepted Answer

Answering your edit :

If you really want to fake multiple inheritance, you can use the magic function __call().

This is ugly though it works from class A user's point of view :

class B {
    public function method_from_b($s) {
        echo $s;

class C {
    public function method_from_c($s) {
        echo $s;

class A extends B
  private $c;

  public function __construct()
    $this->c = new C;

  // fake "extends C" using magic function
  public function __call($method, $args)

$a = new A;

Prints "abcdef"

12/10/2008 3:25:04 PM

You cannot have a class that extends two base classes. You could not have.

// this is NOT allowed (for all you google speeders)
Matron extends Nurse, HumanEntity

You could however have a hierarchy as follows...

Matron extends Nurse    
Consultant extends Doctor

Nurse extends HumanEntity
Doctor extends HumanEntity

HumanEntity extends DatabaseTable
DatabaseTable extends AbstractTable

and so on.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow