PHP Traits

PHP-SAIGON MEETUP

12 January 2015

Hong Viet Nguyen

What are Traits?

- A method of code reuse

 

- reduce some limitations of single inheritance by allowing to reuse sets of methods freely in several independent classes living in different class hierarchies

 

Similar to a class, but only intended to group functionality 

 

- Not possible to instantiate a Trait on its own 

 

- Enables horizontal composition in addition to tradtional inheritance

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();

Examples

Examples

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 AliasedTalker {
    use A, B {
        A::smallTalk insteadof B;
        B::bigTalk insteadof A;
        A::bigTalk as talk;
    }
}

// print 'bA'
$talker = new Talker();
$talker->smallTalk();
$talker->bigTalk();

// print 'aBA'
$aliasedTalker = new AliasedTalker();
$aliasedTalker->smallTalk();
$aliasedTalker->bigTalk();
$aliasedTalker->talk();

Examples

Traits vs. Abstract Classes

Similar:

- Both cannot be instantiated by themselves

 

Difference:

- Traits are not inheritable

Traits vs. Interfaces

- Traits are interfaces with implementation

Design Concept

Horizontal Design

- Reduce duplicate code

- Create a more extendable application

Vertical Design

Horizontal + Vertical Design

Good & Bad

Advantages

- Reduces the amount of code needed

 

- Code can be reused by multiple classes

 

Reduces Dependency Injection requirements 

 

 

Disadvantages

- Harder to navigate code

 

- Property conflicts

 

- Method conflicts

References

Q & A

Thank you !

PHP Traits

By Hong Viet Nguyen

PHP Traits

  • 917