PHP tutorial: how to use Traits

In this tutorial I will speak aboout the traits in PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

I will create two classes:

class show
{
public function say()
{
echo 'Hello ';
}
}

class get extends show
{

}

$a = new get();
$a->say();

This code will display:

Hello

Now I can use a trait to add new infoormation in my first class:

trait repeat{
public function say()
{
parent::say();
echo 'World!';
}
}

Then, I will call it bu adding repeat in the get class:

class get extends show
{

use repeat;

}

Video tutorial:









Leave a Comment