PHP Traits

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:

  • The trait method can be used by the different child classes.
  • The method can use a public, private, and protected modifier.
  • It consists of both abstract and non-abstract methods.
  • It reduces code duplication hence it saves a lot of time.
  • The trait can not be instantiated means no object can be created from the trait class.

Basic Difference Between Inheritance Vs Trait

Inheritance supports only single inheritance while trait is used to support multi-inheritance.

How To Declare Trait

The trait can be declared using the trait keyword.

General Syntax Of Trait

Trait MyTrait { ... }

Using Traits Inside The Classes

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;

Trait Example

Let us create two trait class and use it inside the child class to show multiple inheritance features.

Source Code

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();
Try it now

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.

Web Tutorials

PHP Traits
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4