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()
    {
        if ($this->isSafe()) {
            $this->walkMove();
        } else {
            $this->flyMove();
        }
    }

    private function isSafe() {
        return true;
    }
}

$h = new Bird();
$h->move();

The function move() checks if it is safe to walk and if it is we execute the walkMove function from the WalkAble trait. When it is not safe we fly with the flyMove function from the FlyAble trait.

This is still a very simple example but it shows the key concept of trait that we can implement functionality in a very flexible way. Combined with inheritance and interfaces this is very powerful.

When we add another animal like a monkey we can simply tell the monkey we is only able to walk. The logic of walking we have defined only once in the trait and we don’t get a complex hierarchy of classes.

class Monkey {
    use WalkAble {
        WalkAble::move as walkMove;
    }

    function move()
    {
        $this->walkMove();
    }
}

One thought on “Advanced example of PHP traits”

Comments are closed.