PHP Trait

PHP Trait

Last Updated on Mar 22, 2023

Introduction

Do you remember when we talked about inheritance?

A class can extend only one class. But what if you wanted to inherit multiple classes and have their functionalities in your current class?

The answer is Traits

Trait

We use traits to be able to solve the problem mentioned above. We define the trait like this:

<?php
Trait Example{

}

Then all the methods go inside here.

Now in the class that is going to inherit these functionalities instead of extend we use the word “use” inside the class like this;

Class Human{
    use Example;
}

Now your Human has all the functionalities defined in Example trait.

Trait Example{
    public function sayHello(){
        echo "hello World";
    }
}

Class Human {
    use Example;
}

$human = new Human();
$human->sayHello();
// hello World

You have another trait and you want to use those functionalities as well? No problem.

<?php
Trait Example{
    public function sayHello(){
        echo "hello World";
    }
}

Trait Name{
    public function sayName(){
        echo "my name is Amir";
    }
}

Trait Message{
    public function sayMessage(){
        echo "This is my message for you";
    }
}

Class Human {
    use Example,Name,Message;
}

$human = new Human();
$human->sayHello();
// hello World
$human->sayName();
// my name is Amir
$human->sayMessage();
// This is my message for you
https://youtu.be/KFfQYUsJrIM

Conclusion

Now you know about trait in PHP.

I recommend you to open a PHP files and define multiple traits. then try to use all of them in one class.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • trait in PHP
  • trait vs class
  • using mulitple traits

Category: programming

Tags: #php #oop

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses