Traits don’t take property superscripts?

Asked

Viewed 143 times

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?

  • 1

    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.

1 answer

5


This is not a mistake, it’s a warning.

A trait can insert properties in a class. If a class has a property identical to that of the trait, you get the warn Strict Standards, otherwise you receive a fatal error.

Information obtained of this website.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.