Trait in PHP Object Oriented Programming
- 2020年5月11日
- 技術情報
Today I will talk about trait and its sample usages.In the Object Oriented Inheritance, a child class can only extend only one parent class.So what if the child class has to extend more than one parent classes? OOP trait is the answer for this problem as child classes can extend many traits as they want.Check out the samples below.
Here is the sample usage of a trait
<?php
trait Trait1 {
public function print() {
echo "lets extend more than one trait!";
}
}
class Home {
use Trait1;
}
$obj = new Home();
$obj->print();
?>
Now, Lets extend more than one trait.
<?php
trait Trait1 {
public function print1() {
echo "I am the trait1";
}
}
trait Trait2 {
public function print2() {
echo "I am the trait2";
}
}
class Home {
use Trait1,Trait2;
}
$obj = new Home();
$obj->print1();
$obj->print2();
?>
By Yuuma
yuuma at 2020年05月11日 11:27:03