What is traits?
PHP supports only single inheritance: a child class can inherit only from one single parent class.
but if a class need to inherit multiple inheritence concept then you can use traits to solve this problem.
To define a trait, you use the trait keyword.
To use a trait in a class, you use the use keyword. All the trait’s methods are available in the class where it is used. Calling a method of a trait is similar to calling an instance method.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
Traits can define both static members and static methods.
Syntax
File Name :
<?php
trait TraitName {
// write code here...
}
?>
How to use Traits?
To use a trait in a class, use the use keyword:
File Name :
<?php
class MyClass {
use TraitName;
}
?>
Example
File Name :
<!DOCTYPE html>
<html>
<body>
<?php
trait show {
public function show_msg() {
echo "Hello Sana! ";
}
}
class Mahira_Mahtab {
use show;
}
$obj = new Mahira_Mahtab();
$obj->show_msg();
?>
</body>
</html>
Using Multiple Traits
File Name :
<?php
trait Addition{
public function add($var1,$var2){
return $var1+$var2;
}
}
trait Multiplication {
public function multiply($var1,$var2){
return $var1*$var2;
}
}
class Action {
use Addition;
use Multiplication;
public function calculate($var1,$var2){
echo "Ressult of addition:".$this->add($var1,$var2) ."\n";
echo "Ressult of multiplication:".$this->multiply($var1,$var2);
}
}
$obj = new Action();
$obj->calculate(2,3);
?>
Example
File Name :
<?php
trait Hello {
public function say_hello() {
echo "Hello Sana!";
}
}
trait Hi {
public function say_hi() {
echo "Hi Sana!";
}
}
class Welcome {
use Hello;
}
class Welcome2 {
use Hello, Hi;
}
$obj = new Welcome();
$obj->say_hello();
echo "<br>";
$obj2 = new Welcome2();
$obj2->say_hello();
$obj2->say_hi();
?>
Previous
Next