How do I use traits in PHP 5.4

January 31, 2012

The biggest change in PHP 5.4 is the addition of traits to the object-oriented programmability. Traits prevent code duplication by allowing multiple classes to include a collection of methods implemented as a trait. This means multiple classes can include the same method implementations without duplicating code.

Traits improve on interfaces because they include not only the function definition, but also the implementation. Traits can also use other traits, meaning that one trait could be a collection of others. So, if you had traits Roll and Bounce, you could have trait Movements that used both Roll and Bounce.

trait HelloWorld {
    public function sayHello() {
        echo 'Hello ';
    }

    public function sayWorld() {
        echo 'World!';
    }
}

class MyClass {
    use HelloWorld;
    public function sayHelloWorld() {
        $this->sayhello();
        $this->sayWorld();
    }
}

$h = new MyClass();
$h->sayHelloWorld();      // outputs "Hello World!"

In implementing traits, the keywords trait and insteadof were added to PHP. Usage of trait is outlined above. The PHP keyword insteadof is used for conflict resolution. Here’s an example of how to use insteadof:

trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}

class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive