Author

Multiple Inheritance in PHP

Image

by Samarth Sinha on 2017-03-06 03:02:46

Multiple Inheritance is a feature of Object Oriented Programming which inherits features from more than one object or class. We use Interfaces to implement them in more than one class. 

interface I1 {
    public function fun1();
    public function fun2();
}
interface I2 {
    public function fun3();
    public function fun4();
}
class A {
    public function fun1(){ //do something }
    public function fun2(){ //do something }
    public function fun3(){ //do something }
    public function fun4(){ //do something }
}
$a = new A();
$a->fun1();

In the above example if I remove the implements I1, I2 from the class A our class will work the same way as before. So interface doesn't really solve the problem of multiple inheritance. So for using Multiple Inheritance in PHP we should use traits. In traits we can also define functions. So the example of Multiple Inheritance in PHP will be:

trait T1 {
    public function fun1(){ //do something }
    public function fun2(){ //do something }
}
trait T2 {
    public function fun3(){ //do something }
    public function fun4(){ //do something }
}
class A {
    use T1, T2;
}
$a = new A();
$a->fun1();

In the above example if I remove use T1, T2 from the class A the line $a->fun1() will show the error that fun1 is not defined. In this example the class is getting properties from the traits which fulfils the condition of Inheritance and getting properties from more than one traits satisfies Multiple Inheritance.


Viewer Comments (1)

About the Author

  • avatar
    Samarth Sinha

    My name Samarth Sinha. I work on developing Web Applications using PHP and MySQL and in different frameworks of PHP like Laravel, CakePHP, CodeIgnitor and Smarty. In databases I have worked in MySQL and Postgres. I started this blog to share my knowledge to those who wants to start developing Web Applications using PHP.