QRdvark.com

Simulating Multiple Inheritance With PHP Traits

Simulating Multiple Inheritance With PHP Traits

Contents

  1. Abstract
  2. Why does PHP not have Multiple Inheritance?
  3. The Solution

Abstract

The PHP language, like java, does not natively support multiple inheritance. For some this is a problem for which many solutions have been positted. Here is one solution that makes use of PHP traits.

Why does PHP not have Multiple Inheritance?

The problem with multiple inheritance comes about when a class extends two classes, and each of the two classes has a method of the same name. PHP, like Java, has no way of discerning which class should take precedence. In Python, this issue is resolved simply by declaring that method in the the first class extended takes precedence and that is the method which will be used. Any method of the same name in subsequent classes is ignored.


<?php

class class_1{

    public function 
hello$name )
    {
        return 
"Hello $name";
    }
}

class 
class_2{

    public function 
hello$name )
    {
        return 
"Gday $name";
    }
}

class 
my_class extends class_1 class_2{

    public function 
greeting$name )
    {
        return 
$this->hello$name );
    }
}

$obj = new my_class;
echo 
$obj->greeting"Kev" );

?>

The above code shows the behaviour that we require, in extending two classes, however, this will result in an error like this:

PHP Parse error: syntax error, unexpected 'class_2' (T_STRING), expecting '{' in /home/kevin/Desktop/test.php on line 19

The Solution

In PHP 5.4, the concept of traits was introduced to deal with the issues of inheritance. This capability can be used to mimic the Python style of inheritance we requre.


<?php

trait class_1
{
        public function 
hello$name )
        {
                return 
"Hello $name";
        }
}

trait 
class_2
{
        public function 
hello$name )
        {
                return 
"Gday $name";
        }
}

class 
my_class
{
        use 
class_1class_2
        
{
                
class_1::hello insteadof class_2;
        }
}

$obj = new my_class();
echo 
$obj->hello"Kev" );

?>

The code above uses PHP traits rather than class names. By using traits, The name of the class which is to take precedence can be specified and PHP will silently ignore any possible collisions. In this instance, the class_1 class method takes precednce and so the output is "Hello Kev" rather than "Gday Kev" as specified in the class_2 class.