這篇文章要為大家介紹一下使用PHP中的trait能力的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

相信大家對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
推薦學習:php影片教學
#以上是如何使用PHP中的trait能力的詳細內容。更多資訊請關注PHP中文網其他相關文章!