PHP 5.4 – Code reuse using Traits

Traits enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. PHP being a single inheritance language, traits enables horizontal composition of behavior – the application of class members without requiring inheritance. I’ll cover Traits in a separate post itself.

Below is a artificial example from the PHP documentation.


<?php

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

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

class MyHelloWorld
{
 use Hello, World;
 public function sayExclamationMark()
 {
 echo '!';
 }
}

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

?>

Which will output:
Hello World!

Leave a Reply

Your email address will not be published. Required fields are marked *

*