Traits in PHP

In this tutorial, we will learn about Traits in PHP. The trait is similar to a class but It isn't permitted to instantiate a Trait on its own. Traits are mainly used to declare methods that can be used in multiple classes. PHP only supports a single level inheritance(means we can inherit one class from another). But with the help of Traits, we can use freely use methods in different class hierarchies.

In PHP we use trait keyword to declare a Trait.

Please check out the following example code to know the basic syntax of Trait.

<?php

trait TraitOne{
public function hello() {
    echo "Hello User! ";
  }
}

?>

Now we will see how to use Trait in class.

<?php
trait TraitOne{
public function hello() {
    echo "Hello User! ";
  }
}

trait TraitTwo{
public function bye() {
    echo "Bye Bye! ";
  }
}

class Example{
  use TraitOne;
  use TraitTwo;
}

$obj = new Example();
$obj->hello();
$obj->bye();
?>

Note! use keyword is used to access Trait in class.

Spread the love
Scroll to Top
×