As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
Lets first see what happens if you inherit two classes. For demostration purpose i create two classes one and two.
class one{
public function printFirst(){
echo "class one";
}
}
class two{
public function printSecond(){
echo "class two";
}
}
Extend class one two.
class some extends one two
{
public function printValues()
{
echo "hi there";
}
}
$demo = new Some;
echo $demo->printValues();
echo $demo->printFirst();
When you execute this code, it will give following error.PHP Parse error: syntax error, unexpected 'two' (T_STRING), expecting '{' i n /var/www/srinu/traits.php on line ..
Now let’s check what happens, if we use traits.For using trait in a class, use use keyword and trait name.
**In PHP we can use more than one trait in a class.
// Define trait one
trait one{
public function printFirst(){
echo "first";
}
}
// Define trait two
trait two{
public function printSecond(){
echo "second";
}
}
class some
{
use one,two; // Calling traits
public function printValues()
{
echo "hi there";
}
}
$demo = new Some;
echo $demo->printFirst();
echo $demo->printSecond();
Now this time we didn’t get any error, it executed perfectly and printed the desired result.




No comments:
Post a Comment