Traits in PHP

php interface vs abstract class
Static methods in PHP OOP

In this article, you will learn traits in PHP.

PHP – What are Traits?

In PHP, you can inherit from only one parent class. Traits overcome this limitation of PHP and allow you to inherit multiple behaviors.

A trait is a class that contains both abstract and non-abstract methods. Different classes can use these methods in their own way. The trait methods can be public, private, or protected with respect to their access modifiers.

trait keyword declares a trait. Look at the following syntax of traits in PHP.

<?php
trait FirstTrait {
  // some code...
}
?>

To use a trait in a class, use a keyword followed by the name of the Trait is used. Syntax of using trait in a class is given below.

<?php
class ABC {
  use FirstTrait;
}
?>

Example of Trait in PHP

<?php
trait FirstTrait {
public function message1() {
    echo "PHP is fun! ";
  }
}

class Hello {
  use FirstTrait;
}

$hello = new Hello();
$hello->message1();
?>
  • In the above example, we declare a trait FirstTrait that contains a method message1.
  • We create our class Hello that use the FirstTrait.
  • Now, when we create the object of our class, we have all the methods of the trait used by this class, like message1() method in this example.

Using Multiple Traits in a class – PHP

As we mentioned earlier, PHP does not support multiple inheritances by which a child class can inherit more than one parent class. This missing feature of OOP is overcome by traits to much extent. In the following example, we will apply multiple traits in the classes.

<?php
trait trait1 {
  public function message1() {
    echo "PHPis fun! ";
  }
}

trait Trait2{
  public function message2() {
    echo "Traits avoid redundancy of code!";
  }
}

class Hello {
  use Trait1;
}

class Welcome {
  use Trait2, Trait2;
}

$obj_1 = new Trait1();
$obj_1->message1();

$obj_2 = new Trait2();
$obj_2->message1();
$obj_2->message2();
?>
  • In the above example, we create two traits named as Trait1 and Trait 2. Trait1 contains single method messge1 and the Trait2 contains two methods, message1 and message2.
  • To use multiple traits in a class, separate each trait by comma.
  • Now, we can use single or both of these trait in our classes. Just like the impementation we have given in the examoke.

Reference to the official PHP 8 documentation of traits.

php interface vs abstract class
Static methods in PHP OOP

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top