PHP中的Traits詳解

2022-08-01 18:24:13 字數 2573 閱讀 4432

<?php

trait drive \n";}}

class person

}class student extends person

}$student = new student();

$student->study();

$student->eat();

$student->driving();

輸出結果如下:

study

eatdriving trait

上面的例子中,student類通過繼承person,有了eat方法,通過組合drive,有了driving方法和屬性carname。

如果trait、基類和本類中都存在某個同名的屬性或者方法,最終會保留哪乙個呢?通過下面的**測試一下:

<?php 

trait drive

public function driving()

}class person

public function driving()

}class student extends person

}$student = new student();

$student->hello();

$student->driving();

輸出結果如下:

hello student

driving from drive

因此得出結論:當方法或屬性同名時,當前類中的方法會覆蓋 trait的 方法,而 trait 的方法又覆蓋了基類中的方法。

如果要組合多個trait,通過逗號分隔 trait名稱:

use trait1, trait2;

如果多個trait中包含同名方法或者屬性時,會怎樣呢?答案是當組合的多個trait包含同名屬性或者方法時,需要明確宣告解決衝突,否則會產生乙個致命錯誤。

<?php

trait trait1

public function hi()

}trait trait2

public function hi()

}class class1

輸出結果如下:

使用insteadof和as操作符來解決衝突,insteadof是使用某個方法替代另乙個,而as是給方法取乙個別名,具體用法請看**:

<?php

trait trait1

public function hi()

}trait trait2

public function hi()

}class class1

}class class2

}$obj1 = new class1();

$obj1->hello();

$obj1->hi();

echo "\n";

$obj2 = new class2();

$obj2->hello();

$obj2->hi();

$obj2->hei();

$obj2->hehe();

輸出結果如下:

trait2::hello

trait1::hi

trait2::hello

trait1::hi

trait2::hi

trait1::hello

<?php

trait hello

}class class1

}class class2

}$obj1 = new class1();

$obj1->hello(); # 報致命錯誤,因為hello方法被修改成受保護的

$obj2 = new class2();

$obj2->hello(); # 原來的hello方法仍然是公共的

$obj2->hi(); # 報致命錯誤,因為別名hi方法被修改成私有的

trait 也能組合trait,trait中支援抽象方法、靜態屬性及靜態方法,測試**如下:

<?php

trait hello

}trait world

abstract public function getworld();

public function inc()

public static function dosomething()

}class helloworld

}$obj = new helloworld();

$obj->sayhello();

$obj->sayworld();

echo $obj->getworld() . "\n";

helloworld::dosomething();

$obj->inc();

$obj->inc();

輸出結果如下:

hello

world

get world

doing something

12

php中traits學習筆記

越來越多的框架和 開始使用traits方式去組織一些功能,這是非常高效的 組織結構。通過trait來減少不必要的類繼承關係,讓 更加復用,形成可以拔插的 集合。通過逗號分隔,在 use 宣告列出多個 trait,可以都插入到乙個類中。單個的例子 trait seller class myseller...

php中traits學習筆記

越來越多的框架和 開始使用traits方式去組織一些功能,這是非常高效的 組織結構。通過trait來減少不必要的類繼承關係,讓 更加復用,形成可以拔插的 集合。通過逗號分隔,在 use 宣告列出多個 trait,可以都插入到乙個類中。單個的例子 trait seller class myseller...

traits技術詳解

stl模版庫非常強調軟體的復用,traits技術是採用的重要手段。traits提取不同類的共性,以便能統一處理。traits技術依靠顯示模版特殊化來把 中因型別不同而發生變化的片段拖出來,用統一的介面來包裝。這個介面可以包含乙個c 類所能包含的任何東西,如內嵌型別 成員函式 成員變數。作為客戶的模版...