PHP5.4 introduced a new feature named trait. Trait can improve code reusability and remove the limitation of the lack ofmultiple inheritance in PHP. We can use trait to gain the benefits of multiple inheritance Here are some basic concepts of traits.
I am declaring our first trait here.
trait our_trait1
{
public function foo() { echo ‘I am in trait function foo’; }
public function bar() { echo ‘I am in trait function bar’; }
}
Next we create a class
class our_class1
{
use our_trait1; //using our trait
}
$class_obj = new our_class1();
$class_obj->foo(); // will print I am in trait function foo
$class_obj->bar(); // will print I am in trait function bar
In the above example we use single inheritance.
Next is multiple inheritance
trait our_trait1
{
public function foo() { echo ‘I am in our_trait1 function foo’; }
}
trait our_trait2
{
public function bar() { echo ‘I am in our_trait1 function bar’; }
}
Next we create a class
class our_class1
{
use our_trait1,our_trait2; //using our trait
}
$class_obj = new our_class1();
$class_obj->foo(); // will print I am in our_trait1 function foo
$class_obj->bar(); // will print I am in our_trait2 function bar
This is a simple introduction to traits.
More details can be found in
http://in2.php.net/traits