What are Traits in PHP?
PHP only allows one type of inheritance, so a child class can only get its traits from one parent class.
So, what happens if a class needs to get more than one behavior? This problem can be fixed by OOP traits.
With traits, you can define methods that can be used in more than one class. Traits can have methods and abstract methods that can be used in more than one class, and the methods can have any access modifier (public, private, or protected).
The trait keyword is used to declare a trait:
Syntax
<?php
trait Trait_Name {
// your code…
}
?>
Syntax
<?php
class Class_Name {
use Trait_Name;
}
?>
Example
<!DOCTYPE html>
<html>
<body><?php
trait test1 {
public function result() {
echo \”Coderazaa is easy to understand! \”;
}
}class Show {
use test1;
}$obj = new Show();
$obj->result();
?></body>
</html>
Output
Coderazaa is easy to understand!
Using Multiple Traits in PHP
Let\’s look at another example:
<!DOCTYPE html>
<html>
<body><?php
trait result1 {
public function res1() {
echo \”Coderazaa is simple! \”;
}
}trait result2 {
public function res2() {
echo \”Coderazaa reduces code stress!\”;
}
}class Test {
use result1;
}class Test2 {
use result1, result2;
}$objct = new Test();
$objct->res1();
echo \”<br>\”;$objct2 = new Test2();
$objct2->res1();
$objct2->res2();
?></body>
</html>
Output
Coderazaa is simple!
Coderazaa is simple! Coderazaa reduces code stress!