
批改狀態(tài):合格
老師批語:trait, 就像是你們單位招的臨時工, 活都是他們干的, 但并得不到類中原生成員的身份, 出事了, trait還能頂包: 這是第三方類庫有Bug...
1、代碼
<?php
trait A
{
function put(){
return 'A當(dāng)前類名'.__CLASS__;
}
}
trait B
{
function put(){
return 'B當(dāng)前類名'.__CLASS__;
}
}
trait AB
{
use A,B{
B::put insteadOf A;//使用B中的同名方法代替A中的同名方法insteadOf;
A::put as aput;//給A中的同名方法取個別名as;
}
public function getf(){
return 'AB中調(diào)用的方法:'.__METHOD__;
}
}
class Work
{
use AB{
//修改trait中的方法訪問控制
getf as protected gf;
}
}
echo (new Work())->put(),'<br>';
echo (new Work())->aput(),'<br>';
echo (new Work())->getf(),'<br>';
echo (new Work())->gf(),'<br>';
2、運行結(jié)果
優(yōu)點:trait類似于函數(shù)庫,任何class都可以調(diào)用,可以節(jié)省代碼重寫率;
不適合放在父類(含接口類)或者子類中的方法可以通過trait來實現(xiàn);
缺點:trait無法實列化(不像函數(shù)可以隨時調(diào)用執(zhí)行),只能通過實列類來執(zhí)行;
1、案例代碼
<?php
// 接口
interface iP
{
public static function getn(int $a,int $b);
}
// trait
trait tC
{
public static function computer(int $a,int $b)
{
return "{$a}×{$b}=".($a*$b).'<br>';
}
}
// 工作類
class P implements iP
{
use tC;
public static function getn (int $a, int $b)
{
$arr=range($a,$b);
for($i=0;$i<count($arr);$i++){
if(($i+1)<count($arr)){
// 靜態(tài)函數(shù)無法使用$this;但可以使用new self();
echo (new self)->computer($arr[$i],$arr[$i+1]);
// echo static::computer($arr[$i],$arr[$i+1]);
// echo tC::computer($arr[$i],$arr[$i+1]);
}
}
}
}
// 客戶端
echo "<style>
input{
height:30px;
width:30px;
vertical-align: middle;
font-size:18px;
}
button{
background-color:lightblue;
height:30px;
width:80px;
}
</style>";
echo"<h1>自動生成<input/>-<input/>的乘法公式:</h1>";
print_r(P::getn(0,5));
echo "<button>生成</button>";
1、案例運行結(jié)果
1、trait方法集:可以組合使用; 引用多個trait, 中間用逗號分開;
2、trait解決方法命名沖突的方法:
替代:關(guān)鍵字`insteadOf`
別名:關(guān)鍵字`as`
別名可以改變成員訪問控制:遵循public>protected>private
3、使用trait時,用關(guān)鍵字use
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號