5
According to the excerpt from the PHP Handbook
A Trait is intended to reduce some simple inheritance limitations by allowing a developer to reuse sets of methods freely...
Take an example:
trait Stack
{
protected $items = [];
public function say()
{
return 'stack';
}
}
class Overflow
{
use Stack;
public function stackoverflow()
{
return $this->say() . ' overflow';
}
}
$o = new Overflow;
echo $o->stackoverflow(); // stack overflow
In the above case, we import the method say
for the class Overflow
.
It is also possible to override the trait
.
class Overflow
{
use Stack;
public function say()
{
return 'overflow';
}
}
echo (new Overflow)->say(); // overflow
However, when I try to overwrite the property $items
of trait Stack
, the following error is generated.
Example:
class Overflow
{
use Stack;
protected $items = []; // mesma propriedade de "Stack"
}
Error generated:
Strict Standards: Overflow and Stack define the same Property ($items) in the Composition of Overflow. This Might be incompatible, to improve Maintainability consider using accessor methods in traits Instead
Why it is not possible to redeclare a property in a Trait
? This is outside the goal by which he was created?
This is not a mistake as your code will continue to work smoothly. It’s just a warning that you should try to implement it otherwise.
– gmsantos