Traits in PHP, allows to use or share its code in multiple classes without inheritance. Following are the features of using traits in PHP.
- Trait is introduced in PHP version 5.4
- It allows to reuse code in multiple classes.
- Traits objects cannot be created. it can only be used by classes.
- Trait removes the problem of single inheritance, by getting used in different classes despite of hierarchy.
- Class can use more than one traits.
- A trait can use another trait.
Syntax
trait traitname{
public function function_name(arguments){
//set of statements
}
}
Create a Trait
trait myTrait{
public function sayHello(){
return "Hello";
}
}
Using a Trait
To use a trait in a class, use keyword is used with trait name.
<?php
trait myTrait{
public function sayHello(){
return "Hello";
}
}
class myClass{
use myTrait;
}
$obj = new myClass();
echo $obj->sayHello();
?>
Using multiple Traits in a class
To use multiple traits in a class, use keyword is followed by traits name are separated by comma.
Syntax
<?php
class myclass{
use trait1, trait2, trait3;
}
?>
Example
<?php
trait myTrait{
public function sayHello(){
return "Hello";
}
}
trait Byee{
public function sayBye(){
return '<br/>'. "Bye";
}
}
class myClass{
use myTrait, Byee;
}
$obj = new myClass();
echo $obj->sayHello();
echo $obj->sayBye();
?>