4

This is how classes do it?

Class Main 
{
    $this->a = new A();
    $this->b = new B();
    $this->c = new C();

    $this->b->doTranslate($this->a->saySomething());
}

And this is how traits do it, not?

Class Main {
    use A;
    use B;
    use C;

    $this->doTranslate($this->saySomething());
}

I don't have much knowledge about traits at all, but by looking at new PHP 5.4 trait examples, they only seem to help in a single case. A class only be extended once to use $this together, but we can use multiple traits.

Question 1: Is it the only advantage of using traits over basic classes?

Question 2: If trait A, B, and C all have a function named example(), when I try $this->example(); how PHP is going to determine which trait will be used? What's going to happen?

Additionally, instead of writing a wall of text; just provive me a short code example with a short brief that I can have a look and undertstand. I'm not familiar with traits and don't know what they truly are.

4

2 回答 2

5

You can do many things with traits. I used it in my framework for example as Singleton and Getter/Setter.

trait Singleton
{
    protected static $_instance;

    protected function __construct(){}

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new static();
        }
        return self::$_instance;
    }
}

Another interesting use is for Aspect Oriented Programming. The answer would be to long to explain. Have a look here and here.

Question 2: If the traits have the same method than there will be a fatal error. You have to use the insteadof operator for conflict resolution. Look here

于 2013-03-01T18:56:50.043 回答
0

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. Traits have been available in PHP since 5.4. A trait is a PHP file that uses the trait keyword instead of class.One of the benefits of traits over classes and inheritance is the ability to use multiple traits inside one class. This is sometimes compared to multiple inheritance which is a feature PHP does not support.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Read full article from here What are traits in PHP ?

于 2019-01-17T12:12:00.323 回答