Generally, a child class inherits only one parent class but using the PHP trait, you can create multiple inheritances.
PHP trait has an abstract and non-abstract method that is used by multiple classes. These methods have the following access modifiers such as (public, private, or protected).
The trait has the followings characteristics:
Inheritance supports only single inheritance while trait is used to support multi-inheritance.
The trait can be declared using the trait
keyword.
Trait MyTrait { ... }
Trait can be used inside the child class by using use
keyword followed by trait name.
To use multiple traits inside the child class, write a comma-separated trait name after the use
keyword.
class MyClass{
use MyTrait;
}
Let us create two trait class and use it inside the child class to show multiple inheritance features.
Source Code
<?php
Trait Greet{
public function greetMessage() {
echo "This is the multiple inheritance concept.";
}
}
Trait Confirmation {
public function responseMessage() {
echo "I hope ,you can learn and understand the concept of trait.";
}
}
class LearningClass {
use Greet, Confirmation;
}
$obj = new LearningClass();
$obj -> greetMessage();
$obj -> responseMessage();
?>
Code Explanation: Here, two treat is created namely greetMessage, responseMessage, and creating a child class i.e LearningClass that uses two traits inside the class hence all the methods in traits will be available in the class.
Creating object using child class i.e LearningClass and then calling $obj->greetMessage() and $obj->responseMessage().
Attention: Do not create object from the traits because it is not valid syntax.