Tutorial Image

PHP - OOP Traits

Generally, a child class inherits only one parent class but using the PHP OOP trait concept is used to create multiple inheritances.

PHP trait has an abstract and non-abstract method that is used by multiple classes. These methods have the followings 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

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.

Trait Example

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

Source Code

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.