Why?

How do classes do this?

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

And how do the traits do it?

 Class Main { use A; use B; use C; $this->doTranslate($this->saySomething()); } 

I have little knowledge of features, but looking at new examples of PHP 5.4 features, they seem to only help in one case. A class only be extended once to use $this together, but we can use multiple traits.

Question 1: Is this the only advantage of using traits over base classes?

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

Also, instead of writing a wall of text; just provide me an example of a short code with a short message that I can look at and take over. I am not familiar with the features and do not know what they really are.

+4
source share
2 answers

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 for aspect-oriented programming. The answer will be a long explanation. Look here and here .

Question 2: If the traits have the same method as the fatal error. You must use the insteadof operator to resolve conflicts. Look here

+4
source

Traits are a mechanism for reusing code in single-inheritance languages ​​such as PHP. The trait is designed to reduce some of the limitations of single inheritance, allowing the developer to freely reuse sets of methods in several independent classes located 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 a class. One of the advantages of properties over classes and inheritance is the ability to use multiple attributes in the same class. This is sometimes compared to multiple inheritance, which PHP does not support.

A trait is similar to a class, but is intended only to group functionality in a detailed and consistent way. It is impossible to create a Trait on your own. This is an addition to traditional inheritance and allows horizontal composition of behavior; that is, the use of class members without the need for inheritance.

Read the full article here. What are the features in PHP?

0
source

All Articles