php中的trait怎么使用?(附示例)
来源:不言
发布时间:2018-12-28 11:24:04
阅读量:1066
自PHP5.4.0 起,PHP实现了一种代码复用的方法,称为trait。为了实际使用trait,trait和class指定类名一样,首先需要指定trait名称,在定义的trait模块中,可以定义方法,下面我们就来看看本篇文章的详细内容。

创建trait所需的任务是就是上面的“确定trait名称”“定义所需方法”。
我们来看一下trait的使用方法
trait的定义
1 2 3 4 5 6 7 | trait 特征名{
function 方法名1() {
}
function 方法名2() {
}
}
|
trait的使用
具体的示例
在下面的代码中,我们准备了这个book类和pen类,并且在这两个类中都有一个计算价格的过程,包括共同的税,所以我们用trait定义了这个过程。
我认为可以通过简单地编写“use TaxCalculator;”来说明可以使用含税计算功能。
如果在book类/ pen类中定义了此值,则要写入的代码量会增加,并且在进行更正时必须修改这两个类。
使用trait会减少代码量,即使发生修复,可维护性也很高,因为它只需要修复TaxCalculator。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | trait TaxCalculator {
private $price;
private $tax = 0.08;
public function taxIncluded() {
return $this->price * (1 + $this->tax);
}
}
class Book {
use TaxCalculator;
public $title;
public $author;
public function __construct($price, $title, $author) {
$this->price = $price;
$this->title = $title;
$this->author = $author;
}
}
class Pen {
use TaxCalculator;
public $color;
public $type;
public function __construct($price, $color, $type) {
$this->price = $price;
$this->color = $color;
$this->type = $type;
}
}
$book = new Book(80, ""红楼梦"", ""曹雪芹"");
$pen = new Pen(10, ""black"", ""sharp"");
echo $book->taxIncluded().PHP_EOL;
echo $pen->taxIncluded().PHP_EOL;
|