Trait
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.
Trait 是一种代码重用的机制,由于PHP语言本身并不像C++等语言一样支持类的多继承,PHP用trait来实现“多继承”。用户可以用Trait声明一个包含属性和方法的对象,类可以引入多个trait并继承其中的属性和方法,以此来实现多继承
Note
- trait 对象不能实例化
Usage
1 |
|
输出1
2 php helloWorld.php
Hello World
用trait实现多继承
1 |
|
输出1
2
3 php c.php
Hello World
Thank you
Precedence
An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.
子类的属性和方法 > trait的属性和方法 > 父类的属性和方法