According to the PHP Manual excerpt
A Trait is intended to reduce some simple inheritance limitations by allowing a developer to freely reuse sets of methods ...
See 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 imported the say
method into the Overflow
class.
It is also possible to override the trait
method.
class Overflow
{
use Stack;
public function say()
{
return 'overflow';
}
}
echo (new Overflow)->say(); // overflow
However, when I try to overwrite the $items
property 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 defines the same property ($ items) in the composition of Overflow. This might be incompatible, to improve maintainability consider using accessor methods in traits instead
Why can not I re-declare a property in Trait
? Is this out of the goal for which it was created?