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

Comments

Use aggregation or interfaces. Multiple inheritance doesn't exist in PHP.

Written by Franck

I'm looking into interfaces as I'm not a big fan of large class hierarchies. But I can't see how interfaces actually do anything?

Written by LOGIC9

Interfaces enable you to "inherit" the API only, not function bodies. It forces class a to implement methods from interface b and c. It means that if you want to inherit behavior you must aggregate member objects of classes b and c in your class a.

Written by Franck

I mean put private $b (instance of b) and private $c (instance of c) in your class a, if that wasn't clear enough.

Written by Franck

Consider using Decorators sourcemaking.com/design_patterns/decorator or Strategies sourcemaking.com/design_patterns/strategy

Written by Gordon

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)
  {
    $this->c->$method($args[0]);
  }
}


$a = new A;
$a->method_from_b("abc");
$a->method_from_c("def");

Prints "abcdef"

Written by Franck
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki