Traits do not accept overrides of properties?

4

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?

    
asked by anonymous 24.02.2015 / 16:35

1 answer

4

This is not an error, it's a warning.

A% of can insert properties into a class. If a class has an identical property of trait , you get warn trait , otherwise you get a fatal error .

Information obtained from this site .

    
24.02.2015 / 18:08