相信大家對trait已經不陌生了,早在5.4時,trait就已經出現在了PHP的新特性中,當然,本身trait也是特性的意思,但這個特性的主要能力就是為了代碼的復用,
我們都知道,PHP是現代化的面向物件語言,為了解決C++多重繼承的混亂問題,大部分語言都是單繼承多介面的形式,但這也會讓一些可以復用的代碼必須通過組合的方式來實作,如果要用到組合,不可避免的就要實體化類或者使用靜態方法,無形中增加了記憶體的占用,而PHP為了解決這個問題,就正式推出了trait能力,你可以把它看做是組合能力的一種變體,
trait A
{
public $a = 'A';
public function testA()
{
echo 'This is ' . $this->a;
}
}
class classA
{
use A;
}
class classB
{
use A;
public function __construct()
{
$this->a = 'B';
}
}
$a = new classA();
$b = new classB();
$a->testA();
$b->testA();
從上述代碼中,我們可以看出,trait可以給應用于任意一個類中,而且可以定義變數,非常方便,trait最需要注意的是關于同名方法的多載優先級問題,
trait B {
function test(){
echo 'This is trait B!';
}
}
trait C {
function test(){
echo 'This is trait C!';
}
}
class testB{
use B, C;
function test(){
echo 'This is class testB!';
}
}
$b = new testB();
$b->test(); // This is class testB!
// class testC{
// use B, C;
// }
// $c = new testC();
// $c->test(); // Fatal error: Trait method test has not been applied, because there are collisions with other trait methods on testC
在這里,我們的類中多載了test()方法,這里輸出的就是類中的方法了,如果注釋掉testB類中的test()方法,則會報錯,因為程式無法區分出你要使用的是哪一個trait中的test()方法,我們可以使用insteadof來指定要使用的方法呼叫哪一個trait,
class testE{
use B, C {
B::test insteadOf C;
C::test as testC;
}
}
$e = new testE();
$e->test(); // This is trait B!
$e->testC(); // This is trait C!
當然,現實開發中還是盡量規范方法名,不要出現這種重復情況,另外,如果子類參考了trait,而父類又定義了同樣的方法呢?當然還是呼叫父類所繼承來的方法,trait的優先級是低于普通的類繼承的,
trait D{
function test(){
echo 'This is trait D!';
}
}
class parentD{
function test(){
echo 'This is class parentD';
}
}
class testD extends parentD{
use D;
}
$d = new testD();
$d->test(); // This is trait D!
最后,trait中也是可以定義抽象方法的,這個抽象方法是參考這個trait的類所必須實作的方法,和抽象類中的抽象方法效果一致,
trait F{
function test(){
echo 'This is trait F!';
}
abstract function show();
}
class testF{
use F;
function show(){
echo 'This is class testF!';
}
}
$f = new testF();
$f->test();
$f->show();
trait真的是PHP是非常靈活的一個功能,當然,越是靈活的東西越需要我們去弄明白它的一些使用規則,這樣才能避免一些不可預見的錯誤,
測驗代碼:
https://github.com/zhangyue0503/dev-blog/blob/master/php/201912/source/trait%E8%83%BD%E5%8A%9B%E5%9C%A8PHP%E4%B8%AD%E7%9A%84%E4%BD%BF%E7%94%A8.php
參考檔案:
https://www.php.net/manual/zh/language.oop5.traits.php
關注公眾號:【硬核專案經理】獲取最新文章
添加微信/QQ好友:【xiaoyuezigonggong/149844827】免費得PHP、專案管理學習資料
知乎、公眾號、抖音、頭條搜索【硬核專案經理】
B站ID:482780532
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/262790.html
標籤:PHP
上一篇:Spring回圈依賴問題的解決
