php从以前到现在一直都是单继承的语言,无法同时从两个基类中继承属性和方法,为了解决这个问题,php出了Trait这个特性。
Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。
<?php
/**
* trait 基本用法
*/
trait R {
function rich () {
//...
}
}
class HH {
use R;
function handsome() {
//...
}
}
$obj = new HH();
$obj->rich();
<?php
trait firstTrait {
function firstMethod() { echo "method1"; }
}
trait secondTrait {
// trait 中也可以用抽象方法
abstract function secondMethod();
}
class firstClass {
// 使用多个 trait:
use firstTrait, secondTrait;
function secondMethod() {
//...
}
}
$obj = new firstClass();
// Valid
$obj->firstMethod(); // Print : method1
// Valid
$obj->secondMethod(); // Print : method2
<?php
trait firstTrait {
function firstMethod() { echo "method1"; }
}
trait secondTrait {
// trait 中使用 trait:
use firstTrait;
function secondMethod() { echo "method2"; }
}
class firstClass {
use secondTrait;
}
$obj= new firstClass();
// Valid
$obj->firstMethod(); // Print : method1
// Valid
$obj->secondMethod(); // Print : method2
<?php
trait firstTrait {
function sameMethodName() { echo "method in firstTrait\n"; }
}
trait secondTrait {
function sameMethodName() { echo "method in secontTrait\n"; }
}
class firstClass {
// 使用firstTrait中的sameMethodName()方法而不是用secondTrait中的。:
use firstTrait, secondTrait {
firstTrait::sameMethodName insteadof secondTrait;
}
}
$obj = new firstClass();
$obj->sameMethodName(); // Print : method in firstTrait
<?php
trait firstTrait {
function sameMethodName() { echo "method in firstTrait\n"; }
}
trait secondTrait {
function sameMethodName() { echo "method in secontTrait\n"; }
}
class firstClass {
use firstTrait, secondTrait {
// 使用firstTrait中的sameMethodName()方法而不是用secondTrait中的。:
firstTrait::sameMethodName insteadof secondTrait;
// 使用secondTrait中的sameMethoName()方法但改名为 anotherMethodName():
secondTrait::sameMethodName as public anotherMethodName;
}
}
$obj = new firstClass();
$obj->sameMethodName();
$obj->anotherMethodName();
特性详细介绍:http://php.net/traits