作為一種擴(kuò)展機(jī)制构资,可以方便的實(shí)現(xiàn)一個(gè)類庫的多繼承問題遮糖。
trait是一種為類似 PHP 的單繼承語言而準(zhǔn)備的代碼復(fù)用機(jī)制冕广。trait為了減少單繼承語言的限制落追,使開發(fā)人員能夠自由地在不同層次結(jié)構(gòu)內(nèi)獨(dú)立的類中復(fù)用方法集盈滴。trait和類組合的語義是定義了一種方式來減少復(fù)雜性,避免傳統(tǒng)多繼承和混入類(Mixin)相關(guān)的典型問題轿钠。
一句話總結(jié):把重復(fù)的方法拆分到一個(gè)文件巢钓,通過 use 引入以達(dá)到代碼復(fù)用的目的。
namespace app\index\controller;
load_trait('controller/Jump'); // 引入traits\controller\Jump
class index
{
use \traits\controller\Jump; //一個(gè)jump方法獨(dú)立出來的疗垛,實(shí)現(xiàn)代碼的復(fù)用
public function index()
{
$this->assign('name','value');
$this->show('index');
}
}
Trait 注意點(diǎn)
一症汹、優(yōu)先級
Trait 方法 > extends 方法 > 類方法
二、Trait 方法名沖突的解決
如下面的情況:
<?php
trait ta {
public function demo () {
echo 'ta';
}
}
trait tb {
public function demo () {
echo 'tb';
}
}
class A {
use ta,tb;
}
$a = new A();
$a->demo();
運(yùn)行會報(bào)錯(cuò):
PHP Fatal error: Trait method demo has not been applied, because there are collisions with other trait methods on A
Trait 方法名沖突了贷腕,解決方法有下:
insteadof
class A {
use ta,tb {
tb::demo insteadof ta;
}
}
運(yùn)行結(jié)果:
tb
tb::demo insteadof ta 這句代碼的意思就是用 tb 中的 demo 方法替代 ta 中的 demo 方法背镇。