What are Traits & how can we be used?
By the PHP 5.4.0 version, PHP executes the method for reusing the code which is called Traits.
The trait is a mechanism for reusing code in a single inherited language, like PHP. The expectation for using the trait is to reduce some of the limitations of single inheritance simply by allowing the developers to reuse the sets of methods in multiple independent classes that are living in different class hierarchies.
Explanation of combining the traits and classes defines in a particular way that reduces the complexity and ignores the common problems which are combined with multiple inheritances and the mixins.
A trait is like a class, the difference is it only aims at group functionality in a compressed and steady way. A trait on its own can never be instantiated. It is an expansion to conventional inheritance and empowers even arrangement of behavior; that is, the use of class individuals without requiring inheritance.
Trait Examples
trait ezcReflectionReturnInfo {
function getReturnType() { // Body }
function getReturnDescription() { // Body }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
}
Multiple Traits Examples
These can be inserted into the class by classifying them in the use statement or separated by commas.
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();
The output will be Hello World!
In case the property is being defined by the traits then a class cannot define the property with the same name, otherwise a fatal error will occur.