# Advanced example of PHP traits

With the introduction of PHP 5.4 traits are included. A trait is a mix between an interface and a class. Look on wikipedia for a more detail description on what traits are. Or check Scala which also uses traits.

When searching on the web for a real world example of using traits I did not find very much which was directly clear and somewhat more complete then FooBar or HelloWorld. So I tried to make a more real life example with animals and give an example how to use traits in PHP 5.4.

We define traits the same way as we define a class in PHP with the keyword trait. A trait can contain functions but does not have a constructor because no instance of a trait can exists. We define two traits, FlyAble and WalkAble. Both traits can contain logic about how to fly and how to walk.

trait FlyAble {
function move() {
echo "Flying to destination";
}
}

trait WalkAble {
function move() {
echo "Walking to destination";
}
}

Then we create a class Bird that uses both FlyAble and WalkAble. A bird can walk on the ground because it has legs and can also fly away because it has wings. With use we tell the class which traits we want to use. Both trait has a method with the same name (move()) so we must alias the methods with FlyAble::move as flyMove otherwise we have a conflict in the method names.

class Bird {
use FlyAble, WalkAble {
FlyAble::move as flyMove;
WalkAble::move as walkMove;
}

function move()
{