Modern new features of PHP series (three) - Trait Overview

     Trait is a new concept introduced in PHP 5.4, the interface looks like a class like both, actually not, Trait can be seen as part of the implementation class, can be mixed with one or more existing PHP class, its role is twofold: What shows that class can do; provide a modular implementation. Trait is a code-multiplexing, provides a flexible mechanism for code reuse single inheritance restriction PHP.

Why Trait

     PHP language using a typical single inheritance model, in this model, we first write a common root class, basic function, and then extend this root class, to create a more specific sub-categories, directly inherited from the parent class implementation . This is called inheritance hierarchy, many programming languages ​​use this mode. Most of the time this typical inheritance model can work well, but if you want two unrelated PHP class with similar behavior, how to do it?

     Trait is to solve this problem born. Trait able to inject a plurality of modular implementation-independent classes, thereby improving code reuse, compliance DRY (Do not Repeat Yourself) principle. For example Laravel underlying logic and user authentication-related soft delete achieve other places have used the Trait to achieve. Laravel comes to AuthController, for example, one of the login, registration and login failure attempts are achieved by Trait:

     

How to create Trait

     Creating Trait is simple, create a class with somewhat similar, except that the keyword is used traitinstead of class, the above ThrottlesLoginexample:

     

     We traitdeclare that the definition of a Trait, then we, like classes define properties and methods to be used in this Trait in.

     Further Trait Nested and combinations, i.e. combined into a Trait Trait by one or more (a plurality of partition), such as AuthenticatesAndRegistersUsersis the case:

     

     使用多个Trait可能会引起命名冲突问题,上面的代码给出了解决方案:使用insteadof关键字,如果AuthenticatesUsersRegistersUsers中都定义了redirectPathgetGuard方法,那么将从AuthenticatesUsers中获取对应方法而不是RegistersUsers。另外还可以使用as关键字为方法起个别名,这样也可以避免命名冲突。

     此外,这里可能没有完整列出,Trait中还支持定义抽象方法和静态方法,其中抽象方法必须在使用它的类中实现。

     这里还需要声明的一点是调用方法的优先级:调用类>Trait>父类(如果有的话),方法可以覆盖,但属性不行,如果Trait中定义了一个属性,如果调用类中也定义这个属性则会报错。

如何使用Trait

     Trait的使用方法也很简单,上面已经显示的很清楚明了,即使用use关键字。

     可能你已经注意到,命名空间和Trait使用的都是use关键字,不同之处在于导入位置,命名空间在类的定义体外导入,而Trait在类的定义体内导入。

注:PHP解释器在编译时会把Trait复制到类的定义体中,但是不会处理这个操作引入的不兼容问题,如果Trait假定类中有特定的属性或方法,需要先确保类中确实有相应的属性或方法。

 

Guess you like

Origin www.cnblogs.com/mzhaox/p/11222199.html