PHP 5.4 New Features - Traits

December 05, 2012 at 19:22

Another great thing that has been added to PHP are the traits. They are an old conception in other programming languages such as Java or C++. They are extremely useful in order to write reuseable code and make your life easier. So what we can do, just to make a quick introduction, is to write down a class which is using the properties and methods of two traits.

trait Weapons {
    private $_weapons = array(1 => 'a sword', 2 => 'an axe', 3 => 'a spear');

    public function choose_weapon($id) {
        echo ' using ' , $this->_weapons[$id];
    }
}

trait Professions {
    private $_professions = array(1 => 'Warrior', 2 => 'Hunter');
}

class Hero {
    use Weapons, Professions; //here we say which traits our class will have access to

    public function __construct($profession) {
        echo $this->_professions[$profession];
    }
}

$hero = new Hero(1);
$hero->choose_weapon(2);

Result:

Warrior using an axe

So the deal is that we don't have to extend the Hero class in order to access the traits. And the best thing is that we can reuse the traits as many times as needed. A problem will accure if we create two methods with the same name, but I am pretty sure that it will be fixed very soon!

there are no comments yet :(

meow + meow =

friends

find me

  • google plus
  • linked in
  • youtube