DEV Community

loading...

Multiple Inheritance with Traits in PHP

supunkavinda profile image Supun Kavinda ・1 min read

Traits in PHP is a powerful way to reduce code duplication.

In inheritance, we can only inherit a single class. Here's an example.

class Object {
    public $width;
    public function setWidth($width) {
         $this -> width = $width;
    }
}

class Box extends Object {

}
$box = new Box;
$box -> setWidth(10);
Enter fullscreen mode Exit fullscreen mode

Here, we used single inheritance. If we needed to use multiple inheritance, we cannot do that with extending. We will need to use Traits for that.

What are traits?

Traits are class-like which contains methods. Traits cannot be instantiated.

Here's a simple trait.

Trait ObjectToArray {
    public function getArray() {
         return get_object_vars($this);
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's use our trait in a class.

class User {
    use ObjectToArray;
    public function __construct($name, $country) {
        $this -> name = $name;
        $this -> country = $country;
    }
}

$user = new User('John', 'USA');
var_dump($user -> getArray());
Enter fullscreen mode Exit fullscreen mode

In the same way you can use multiple traits in a class.

class User {
    use ObjectToArray;
    use ObjectToJSON;
    // and more...
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Traits are quite useful if you need to use the same methods in multiple classes. Traits helps you to keep the code more organized. But, I haven't seen developers using Traits frequently. They tend to use inheritance and interfaces.

I'm not sure about the reason, but, what I assume is that most of PHP devs are not aware of Traits.

Thank you for reading!

Discussion (1)

pic
Editor guide
Collapse
matthewbdaly profile image
Matthew Daly

One potential gotcha with traits is that unlike with mixins, which are a similar mechanism languages like Python use for multiple inheritance, traits work effectively by copying and pasting the content of the trait into the class using them. This means that you can't then create the same method on the class and refer to the parent defined in the trait like you can with mixins.