What is trait in php?

Sometimes you may want to inherit from more than one class. Since this is not possible in PHP and other single inheritance languages like it, we have something called traits.

To read more about inheritance in PHP, check out this shot.

What is a trait?

In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies.

Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.

Syntax

To create a trait class:

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

To access a trait class:


<?php
  class MyNewClass {
  use TraitName;
}
?

Code

Example 1

Let’s see the code below to understand better.

<?php
class MainClass {
public function greeting() {
echo 'Good Day From MainClass'."\n";
}
}
trait DesiredClass {
public function welcome() {
//parent::greeting();
echo 'Welcome To Traits';
}
}
class NewClass extends Mainclass {
use DesiredClass;
}
$myObject = new NewClass();
$myObject ->greeting();
$myObject->welcome();
/* You can uncomment line 10 while commenting out
*line 20 and the result remains the same.
*/
?>

Explanation

  • A base class was defined as MainClass with a single method.

  • The trait class DesiredClass was also created with another method.

  • The NewClass that was created was able to access the method from both the base class and the trait class which we saw in its object $myobject.

Example 2

<?php
trait hello {
public function message1() {
echo "Nature is precious,\n";
}
}
trait world{
public function message2() {
echo "So Let us unite to preserve it";
}
}
class InUnity {
use hello;
}
class WeCan {
use hello, world;
}
$obj = new InUnity();
$obj->message1();
echo "****************\n";
$obj2 = new WeCan();
$obj2->message1();
$obj2->message2();
?>

Explanation

Multiple traits can be created and used by one or more classes. The code above is an example of multiple trait inheritance.

Free Resources