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

18

182

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

Asco answered 10/12, 2008 at 14:2 Comment(7)
Use aggregation or interfaces. Multiple inheritance doesn't exist in PHP.Comer
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?Asco
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.Comer
I mean put private $b (instance of b) and private $c (instance of c) in your class a, if that wasn't clear enough.Comer
Consider using Decorators sourcemaking.com/design_patterns/decorator or Strategies sourcemaking.com/design_patterns/strategyHyperborean
I'd question my design if I think that multiple inheritance the best solution to my problem. I ran down this road and came across this question. As a rule, if you're trying to do something that's not naturally supported by the language, you should question your design. Multiple inheritance seems unduly confusing and clunky.Patriotism
Please consider traits as the correct answer.Bumper
T
22

EDIT: 2020 PHP 5.4+ and 7+

As of PHP 5.4.0 there are "Traits" - you can use more traits in one class, so the final deciding point would be whether you want really an inheritance or you just need some "feature"(trait). Trait is, vaguely said, an already implemented interface that is meant to be just used.


Currently accepted answer by @Franck will work but it is not in fact multiple inheritance but a child instance of class defined out of scope, also there is the `__call()` shorthand - consider using just `$this->childInstance->method(args)` anywhere you need ExternalClass class method in "extended" class.

Exact answer

No you can't, respectively, not really, as manual of extends keyword says:

An extended class is always dependent on a single base class, that is, multiple inheritance is not supported.

Real answer

However as @adam suggested correctly this does NOT forbids you to use multiple hierarchal inheritance.

You CAN extend one class, with another and another with another and so on...

So pretty simple example on this would be:

class firstInheritance{}
class secondInheritance extends firstInheritance{}
class someFinalClass extends secondInheritance{}
//...and so on...

Important note

As you might have noticed, you can only do multiple(2+) intehritance by hierarchy if you have control over all classes included in the process - that means, you can't apply this solution e.g. with built-in classes or with classes you simply can't edit - if you want to do that, you are left with the @Franck solution - child instances.

...And finally example with some output:

class A{
  function a_hi(){
    echo "I am a of A".PHP_EOL."<br>".PHP_EOL;  
  }
}

class B extends A{
  function b_hi(){
    echo "I am b of B".PHP_EOL."<br>".PHP_EOL;  
  }
}

class C extends B{
  function c_hi(){
    echo "I am c of C".PHP_EOL."<br>".PHP_EOL;  
  }
}

$myTestInstance = new C();

$myTestInstance->a_hi();
$myTestInstance->b_hi();
$myTestInstance->c_hi();

Which outputs

I am a of A 
I am b of B 
I am c of C 
Talley answered 17/9, 2015 at 8:16 Comment(1)
This needs more votes, as in most cases, traits would be the implementation people need!Cutlor
C
189

If you really want to fake multiple inheritance in PHP 5.3, 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"

Comer answered 10/12, 2008 at 15:18 Comment(9)
I actually quite like the idea of extending the class Are there any known limitations of doing it this way?Asco
No limitations as far as I know, PHP is a very permissive language for little hacks like this. :) As others have pointed out, it's not the proper OOP way of doing it though.Comer
I love this idea, clean and simple!Unweighed
You will not be able to use protected or private methods.Searles
There is a comment which suggests a way to do this in the php doc, with the same limitation about protected and private methods php.net/manual/fr/keyword.extends.php#98665Ambulate
@wormhit, though, I wouldn't recommend it for use in production, one can use ReflectionClass to access private and protected methods.Curcio
This won't work for Implements, which expects the method to actually exist and the behaviour is pretty much undefined when multiple base classes have a method with the same name. It will also mess up your editor's ability to give you hints.Dvorak
I'm not quite sure why the community has upvoted this answer. initializing the object C is no where near the same as extending a class. With this method you drop support for property visibility and object inheritance. If i saw a coder write this in production based code, i would immediately fire them. The only case or scenario where code like this should be considered acceptable is if your writing a descriptive object, in which case it should probably be static unless your creating instances of the object in memory.Piker
@Searles in order to salvage protected or private visibility you will need to extend an extended class. In most cases this is not ideal.Piker
A
155

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

// 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.

Accidence answered 10/12, 2008 at 14:12 Comment(2)
Can you explain why it is right to first inherit Nurse into Matron, then declare inheritance of HumanEntity into Nurse?Cartel
@Cartel Because Matron has additional qualities of a Nurse, while a nurse has all the qualities of a human. Therefore, Matron is a human nurse and finally has Matron capabilitiesMilda
O
75

You could use traits, which, hopefully, will be available from PHP 5.4.

Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way, which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.

They are recognized for their potential in supporting better composition and reuse, hence their integration in newer versions of languages such as Perl 6, Squeak, Scala, Slate and Fortress. Traits have also been ported to Java and C#.

More information: https://wiki.php.net/rfc/traits

Our answered 24/6, 2011 at 10:50 Comment(4)
Make sure not to abuse them. Essentially they are static functions that you apply to objects. You could create a mess by abusing them.Our
I cannot believe this is not the selected answer.Bumper
@Bumper me too.Spathose
This should be the selected answer as this is now considered as standard.Pilpul
T
22

EDIT: 2020 PHP 5.4+ and 7+

As of PHP 5.4.0 there are "Traits" - you can use more traits in one class, so the final deciding point would be whether you want really an inheritance or you just need some "feature"(trait). Trait is, vaguely said, an already implemented interface that is meant to be just used.


Currently accepted answer by @Franck will work but it is not in fact multiple inheritance but a child instance of class defined out of scope, also there is the `__call()` shorthand - consider using just `$this->childInstance->method(args)` anywhere you need ExternalClass class method in "extended" class.

Exact answer

No you can't, respectively, not really, as manual of extends keyword says:

An extended class is always dependent on a single base class, that is, multiple inheritance is not supported.

Real answer

However as @adam suggested correctly this does NOT forbids you to use multiple hierarchal inheritance.

You CAN extend one class, with another and another with another and so on...

So pretty simple example on this would be:

class firstInheritance{}
class secondInheritance extends firstInheritance{}
class someFinalClass extends secondInheritance{}
//...and so on...

Important note

As you might have noticed, you can only do multiple(2+) intehritance by hierarchy if you have control over all classes included in the process - that means, you can't apply this solution e.g. with built-in classes or with classes you simply can't edit - if you want to do that, you are left with the @Franck solution - child instances.

...And finally example with some output:

class A{
  function a_hi(){
    echo "I am a of A".PHP_EOL."<br>".PHP_EOL;  
  }
}

class B extends A{
  function b_hi(){
    echo "I am b of B".PHP_EOL."<br>".PHP_EOL;  
  }
}

class C extends B{
  function c_hi(){
    echo "I am c of C".PHP_EOL."<br>".PHP_EOL;  
  }
}

$myTestInstance = new C();

$myTestInstance->a_hi();
$myTestInstance->b_hi();
$myTestInstance->c_hi();

Which outputs

I am a of A 
I am b of B 
I am c of C 
Talley answered 17/9, 2015 at 8:16 Comment(1)
This needs more votes, as in most cases, traits would be the implementation people need!Cutlor
R
19

Classes are not meant to be just collections of methods. A class is supposed to represent an abstract concept, with both state (fields) and behaviour (methods) which changes the state. Using inheritance just to get some desired behaviour sounds like bad OO design, and exactly the reason why many languages disallow multiple inheritance: in order to prevent "spaghetti inheritance", i.e. extending 3 classes because each has a method you need, and ending up with a class that inherits 100 method and 20 fields, yet only ever uses 5 of them.

Reverent answered 10/12, 2008 at 14:48 Comment(1)
I'll take issue with your assertion that the OP's request constitutes "bad OO design"; just look at the emergence of Mixins to support the position that adding in methods to a class from multiple sources is a good idea architecturally. I will however give you that PHP does not provide an optimal set of language features to achieve an optimal "design" but that does not mean using the features available to approximate it is necessarily a bad idea; just look at @Franck's answer.Turnpike
J
18

There are plans for adding mix-ins soon, I believe.

But until then, go with the accepted answer. You can abstract that out a bit to make an "extendable" class:

class Extendable{
  private $extender=array();

  public function addExtender(Extender $obj){
    $this->extenders[] = $obj;
    $obj->setExtendee($this);
  }

  public function __call($name, $params){
    foreach($this->extenders as $extender){
       //do reflection to see if extender has this method with this argument count
       if (method_exists($extender, $name)){
          return call_user_func_array(array($extender, $name), $params);
       }
    }
  }
}


$foo = new Extendable();
$foo->addExtender(new OtherClass());
$foo->other_class_method();

Note that in this model "OtherClass" gets to 'know' about $foo. OtherClass needs to have a public function called "setExtendee" to set up this relationship. Then, if it's methods are invoked from $foo, it can access $foo internally. It will not, however, get access to any private/protected methods/variables like a real extended class would.

Jit answered 11/12, 2008 at 6:22 Comment(0)
C
18

Use traits as base classes. Then use them in a parent class. Extend it .

trait business{
  function sell(){

  }

  function buy(){

  }

  function collectMoney(){
  }

}

trait human{

   function think(){

   }

   function speak(){

   }

}

class BusinessPerson{
  use business;
  use human;
  // If you have more traits bring more
}


class BusinessWoman extends BusinessPerson{

   function getPregnant(){

   }

}


$bw = new BusinessWoman();
$bw ->speak();
$bw->getPregnant();

See now business woman logically inherited business and human both;

Carbonous answered 15/9, 2017 at 12:51 Comment(7)
I'm stuck with php 5.3 there's no trait support :DDevinna
Why not use the trait in BusinessWoman instead of BusinessPerson? Then you can have actual multi-inheritance.Ferryman
@SOFe, because BusinessMan can also extend it. So who ever is doing business can extend busines person, and gets traits automaticallyCarbonous
The way you are doing this is no difference from what's possible in single inheritance where BusinessPerson extends an abstract class called human. My point is that your example doesn't really need multi inheritance.Ferryman
I belive till BusinessPerson it was required, BusinessWoman could have directly inherited oth traits. But what I tried here is, keeping both traits in a mediator class and then use it, where ever required. So at I can forget about including both traits if again needed some where else (as per I described BusinessMan). It is all about code styles. If you like to include directly to your class. you can go ahead with that - as you are absolutely right about that.Carbonous
The point is not whether it is required. The point is that your example, regardless of its business-logic-level meaning, does not demonstrate multi-inheritance at all.Ferryman
update for 2021: BusinessNonBinary extends BusinessPersonPustulate
T
10
<?php
// what if we want to extend more than one class?

abstract class ExtensionBridge
{
    // array containing all the extended classes
    private $_exts = array();
    public $_this;

    function __construct() {$_this = $this;}

    public function addExt($object)
    {
        $this->_exts[]=$object;
    }

    public function __get($varname)
    {
        foreach($this->_exts as $ext)
        {
            if(property_exists($ext,$varname))
            return $ext->$varname;
        }
    }

    public function __call($method,$args)
    {
        foreach($this->_exts as $ext)
        {
            if(method_exists($ext,$method))
            return call_user_method_array($method,$ext,$args);
        }
        throw new Exception("This Method {$method} doesn't exists");
    }


}

class Ext1
{
    private $name="";
    private $id="";
    public function setID($id){$this->id = $id;}
    public function setName($name){$this->name = $name;}
    public function getID(){return $this->id;}
    public function getName(){return $this->name;}
}

class Ext2
{
    private $address="";
    private $country="";
    public function setAddress($address){$this->address = $address;}
    public function setCountry($country){$this->country = $country;}
    public function getAddress(){return $this->address;}
    public function getCountry(){return $this->country;}
}

class Extender extends ExtensionBridge
{
    function __construct()
    {
        parent::addExt(new Ext1());
        parent::addExt(new Ext2());
    }

    public function __toString()
    {
        return $this->getName().', from: '.$this->getCountry();
    }
}

$o = new Extender();
$o->setName("Mahdi");
$o->setCountry("Al-Ahwaz");
echo $o;
?>
Truditrudie answered 7/10, 2014 at 0:17 Comment(3)
Your answer should contain an explanation of your code and a description how it solves the problem.Lassa
It's almost self explanatory, but it would be great to have comments along the code.Rockefeller
now if Ext1 and Ext2 both have a function with same name always Ext1 cwill be called, it will not depend on parameters at all.Carbonous
A
6

I have read several articles discouraging inheritance in projects (as opposed to libraries/frameworks), and encouraging to program agaisnt interfaces, no against implementations.
They also advocate OO by composition: if you need the functions in class a and b, make c having members/fields of this type:

class C
{
    private $a, $b;

    public function __construct($x, $y)
    {
        $this->a = new A(42, $x);
        $this->b = new B($y);
    }

    protected function DoSomething()
    {
        $this->a->Act();
        $this->b->Do();
    }
}
Aniakudo answered 10/12, 2008 at 17:2 Comment(1)
This effectively becomes the same thing that Franck and Sam show. Of course if you do choose to explicitly use composition you should be using dependency injection.Turnpike
I
3

Multiple inheritance seems to work at the interface level. I made a test on php 5.6.1.

Here is a working code:

<?php


interface Animal
{
    public function sayHello();
}


interface HairyThing
{
    public function plush();
}

interface Dog extends Animal, HairyThing
{
    public function bark();
}


class Puppy implements Dog
{
    public function bark()
    {
        echo "ouaf";
    }

    public function sayHello()
    {
        echo "hello";
    }

    public function plush()
    {
        echo "plush";
    }


}


echo PHP_VERSION; // 5.6.1
$o = new Puppy();
$o->bark();
$o->plush();
$o->sayHello(); // displays: 5.6.16ouafplushhello

I didn't think that was possible, but I stumbled upon in the SwiftMailer source code, in the Swift_Transport_IoBuffer class, which has the following definition:

interface Swift_Transport_IoBuffer extends Swift_InputByteStream, Swift_OutputByteStream

I didn't play with it yet, but I thought it might be interesting to share.

Illustrate answered 6/2, 2017 at 10:44 Comment(1)
interesting and irrelevant.Fitzger
P
1

I just solved my "multiple inheritance" problem with:

class Session {
    public $username;
}

class MyServiceResponsetype {
    protected $only_avaliable_in_response;
}

class SessionResponse extends MyServiceResponsetype {
    /** has shared $only_avaliable_in_response */

    public $session;

    public function __construct(Session $session) {
      $this->session = $session;
    }

}

This way I have the power to manipulate session inside a SessionResponse which extends MyServiceResponsetype still being able to handle Session by itself.

Praseodymium answered 1/2, 2012 at 10:24 Comment(0)
D
1

If you want to check if a function is public see this topic : https://mcmap.net/q/137680/-how-to-check-if-a-function-is-public-or-protected-in-php

And use call_user_func_array(...) method for many or not arguments.

Like this :

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

class C {
    public function method_from_c($l, $l1, $l2) {
        echo $l.$l1.$l2;
    }
}

class A extends B {
    private $c;

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

    public function __call($method, $args) {
        if (method_exists($this->c, $method)) {
            $reflection = new ReflectionMethod($this->c, $method);
            if (!$reflection->isPublic()) {
                throw new RuntimeException("Call to not public method ".get_class($this)."::$method()");
            }

            return call_user_func_array(array($this->c, $method), $args);
        } else {
            throw new RuntimeException("Call to undefined method ".get_class($this)."::$method()");
        }
    }
}


$a = new A;
$a->method_from_b("abc");
$a->method_from_c("d", "e", "f");
Destinydestitute answered 23/12, 2013 at 10:7 Comment(0)
L
1

You are able to do that using Traits in PHP which announced as of PHP 5.4

Here is a quick tutorial for you, http://culttt.com/2014/06/25/php-traits/

Lialiabilities answered 24/3, 2016 at 13:56 Comment(0)
K
1

One of the problems of PHP as a programming language is the fact that you can only have single inheritance. This means a class can only inherit from one other class.

However, a lot of the time it would be beneficial to inherit from multiple classes. For example, it might be desirable to inherit methods from a couple of different classes in order to prevent code duplication.

This problem can lead to class that has a long family history of inheritance which often does not make sense.

In PHP 5.4 a new feature of the language was added known as Traits. A Trait is kind of like a Mixin in that it allows you to mix Trait classes into an existing class. This means you can reduce code duplication and get the benefits whilst avoiding the problems of multiple inheritance.

Traits

Kolosick answered 6/5, 2017 at 11:13 Comment(0)
L
0

PHP does not yet support multiple class inheritance, it does however support multiple interface inheritance.

See http://www.hudzilla.org/php/6_17_0.php for some examples.

Lyricism answered 10/12, 2008 at 14:7 Comment(1)
Yet? I doubt they will do it. Modern OO discourage multiple inheritance, it can be messy.Aniakudo
L
0

PHP does not allow multiple inheritance, but you can do with implementing multiple interfaces. If the implementation is "heavy", provide skeletal implementation for each interface in a seperate class. Then, you can delegate all interface class to these skeletal implementations via object containment.

Longley answered 10/12, 2008 at 15:21 Comment(0)
B
0

Always good idea is to make parent class, with functions ... i.e. add this all functionality to parent.

And "move" all classes that use this hierarchically down. I need - rewrite functions, which are specific.

Bemis answered 1/5, 2011 at 11:2 Comment(0)
D
-4

class A extends B {}

class B extends C {}

Then A has extended both B and C

Dierdredieresis answered 14/6, 2018 at 14:31 Comment(1)
@rostamiani because this method is also modifying class B. What we want most of the time is to have two unrelated classes B and C (probably from different libraries) and get simultaneously inherited by A, such that A contains everything from both B and C, but B doesn't contain anything from C and vice versa.Ferryman

© 2022 - 2024 — McMap. All rights reserved.