批改状态:合格
老师批语:trait, 就像是你们单位招的临时工, 活都是他们干的, 但并得不到类中原生成员的身份, 出事了, trait还能顶包: 这是第三方类库有Bug...
1、代码
<?phptrait A{function put(){return 'A当前类名'.__CLASS__;}}trait B{function put(){return 'B当前类名'.__CLASS__;}}trait AB{use A,B{B::put insteadOf A;//使用B中的同名方法代替A中的同名方法insteadOf;A::put as aput;//给A中的同名方法取个别名as;}public function getf(){return 'AB中调用的方法:'.__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、运行结果
优点:trait类似于函数库,任何class都可以调用,可以节省代码重写率;
不适合放在父类(含接口类)或者子类中的方法可以通过trait来实现;
缺点:trait无法实列化(不像函数可以随时调用执行),只能通过实列类来执行;
1、案例代码
<?php// 接口interface iP{public static function getn(int $a,int $b);}// traittrait 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)){// 静态函数无法使用$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、案例运行结果
1、trait方法集:可以组合使用; 引用多个trait, 中间用逗号分开;
2、trait解决方法命名冲突的方法:
替代:关键字`insteadOf`别名:关键字`as`别名可以改变成员访问控制:遵循public>protected>private
3、使用trait时,用关键字use
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号