Usage of traits in php

Usage of traits in php

Introduction to traits:

Traits were a concept introduced into php since PHP 5.4. Traits are mainly to improve code reuse. If there are a set of methods which needs to be used in a set of classes you can combine those methods in a trait and then ‘use’ that trait in your desired class.

Why not use abstract class?

This would be a valid question that you would ask. But there are differences in the context in which a trait is used against an abstact class. An abstract class is used in scenarios where we have ‘is a’ relationship between the base class and the derived class. An example of such a relationship is base class ‘Car’ and derived class ‘Maruti’. In this case ‘Maruti’ ‘is a’ type of car. So we can make use of an abstract class ‘Car’ and let the derived class ‘Maruti’ extend it.

Multiple inheritance is not allowed in php. So you cannot inherit more than one abstract class.

Difference between traits and interfaces:

One of the main reasons why interfaces were introduced is to support multiple inheritance. Similarly multiple traits can also be used in a class. But the difference between an interface and trait is, in an interface we only have function declarations and the class that implements that interface should provide definition to these functions. Whereas a trait has functions along with the function definition.

Usage of traits:

The context in which a trait is used is different from an abstract class. Traits are used when we do not have any relationship between the base class (trait) and the classes using that trait. The purpose of trait is not to satisfy inheritance but to re-use a set of functions or code. An example would be suppose we define a trait ‘Move’ having functions like walk(), run(), glide() etc. This trait can be used in disjoint classes like ‘Mammal’, ‘Reptile’ etc. These classes do not have any relation with the trait but are simply using its methods since they require a similar functionality and traits help them in code reuse.

Code sample:

trait Move
{
 public function run()
 {
    echo "It is running<br/>";
 }
 public function glide()
 {
    echo "It is gliding<br/>";
 }
}

Class Mammal
{
    use Move;
}
Class Reptile
{
    use Move;
}

$mammal = new Mammal();
$mammal->run();

$reptile = new Reptile();
$reptile->glide();
Comments are closed.