Why can traits have methods called directly when they are static?

Asked

Viewed 65 times

4

I just made a question about Traits and another question came to me.

If the Traits are mechanisms that facilitate the import of methods, due to the limitations of an inheritance in PHP, because their methods can be accessed statically?

For example:

trait Stack
{
    protected $items = [];

    public static function say()
    {
        return 'stack';
    }

}

echo Stack::say(); // stack

This is not confusing in view of the direction of the implementation of trait in the language?

It is recommended to use a static method from a trait, or it is better to use it in a class?

1 answer

3


After a read on this website, I understood the following:

  1. Members (fields and/or methods) from a trait has a higher priority than those coming from a super class, but smaller than those of the current class.
  2. When two different classes use the same trait, static members of the trait are different for each of the classes.

And there are other things about traits on the linked site, if you have more questions.

Browser other questions tagged

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