首页 > 开发 > Php > 正文

PHP中的Trait 特性及作用

2020-02-21 20:50:51
字体:
来源:转载
供稿:网友

自 PHP 5.4.0 起,PHP 实现了代码复用的一个方法,称为 traits。

Traits 是一种为类似 PHP 的单继承语言而准备的代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用方法集。Traits 和类组合的语义是定义了一种方式来减少复杂性,避免传统多继承和混入类(Mixin)相关的典型问题。

Trait 和一个类相似,但仅仅旨在用细粒度和一致的方式来组合功能。Trait 不能通过它自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用类的成员不需要继承。

Trait是在PHP5.4中加入的,它既不是接口也不是类。主要是为了解决单继承语言的限制。是PHP多重继承的一种解决方案。例如,需要同时继承两个 Abstract Class, 这将会是件很麻烦的事情,Trait 就是为了解决这个问题。它能被加入到一个或多个已经存在的类中。它声明了类能做什么(表明了其接口特性),同时也包含了具体实现(表明了其类特性)

简单使用

首先,当然是声明个 Trait,PHP5.4 增加了 trait 关键字

trait first_trait {function first_method() { /* Code Here */ }function second_method() { /* Code Here */ }}

同时,如果要在 Class 中使用该 Trait,那么使用 use 关键字

class first_class {// 注意这行,声明使用 first_traituse first_trait;}$obj = new first_class();// Executing the method from trait$obj->first_method(); // valid$obj->second_method(); // valid

使用多个 Trait

在同个 Class 中可以使用多个 Trait

trait first_trait{function first_method() { echo "method"; }}trait second_trait {function second_method() { echo "method"; }}class first_class {// now using more than one traituse first_trait, second_trait;}$obj= new first_class();// Valid$obj->first_method(); // Print : method// Valid$obj->second_method(); // Print : method

Trait 之间的嵌套

同时,Trait 之间也可以相互的嵌套,例如

trait first_trait {function first_method() { echo "method"; }}trait second_trait {use first_trait;function second_method() { echo "method"; }}class first_class {// now using use second_trait;}$obj= new first_class();// Valid$obj->first_method(); // Print : method// Valid$obj->second_method(); // Print : method

Trait 的抽象方法(Abstract Method)

我们可以在 Trait 中声明需要实现的抽象方法,这样能使使用它的 Class 必须实现它

trait first_trait {function first_method() { echo "method"; }// 这里可以加入修饰符,说明调用类必须实现它abstract public function second_method();}class first_method {use first_trait;function second_method() {/* Code Here */}}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表