批改状态:合格
老师批语:trait是对象组合的重要工具, 可以一定程度上摆脱对依赖注入的依赖, 让代码更加的简洁
一、Trait组合的同名方法的命名冲突的解决方案
1-当trait同名的时候,有两种方法来解决:
1)把一个同名的替换,语法是insteadOf;
举例说明:
<?php
trait tgrade1
{
public function hy()
{
echo '注册会员享受折扣';
}
}
trait tgrade2
{
public function hy()
{
echo '非会员不打折';
}
}
class Emy
{
use tgrade1,tgrade2
{
tgrade1::hy insteadof tgrade2;
tgrade2::hy as hyen;
}
}
$emy = new Emy;
echo $emy->hy();运行效果:
![]()
2)用别名as,特别注意的是,as 还可以修改trait成员的访问控制。
举例说明:
<?php
trait tgrade1
{
public function hy()
{
echo '注册会员享受折扣';
}
}
trait tgrade2
{
public function hy()
{
echo '非会员不打折';
}
}
class Emy
{
//修改访问权限
// use tgrade1 {eat as protected;}
//修改别名
use tgrade1 {
hy as hy1;
}
}
$emy = new Emy;
echo $emy->hy();
echo '<hr>';
echo $emy->hy1();运行效果:

二、trait 与 interface 接口进行组合
<?php
//trait :trait和interface接口进行组合
if (!interface_exists ('iTime')){
interface iTime
{
public static function index();
}
}
if (!trait_exists('tTime')){
trait tTime
{
public static function index()
{
return '当前时间:'.date("H:i:s");
}
}
}
//实现这个类
if (!class_exists('yuyue')){
class yuyue implements iTime
{
use tTime;
}
}
echo yuyue::index();运行效果:

三、trait 实现接口方法的优缺点是什么?
首先我们要知道什么是 Trait ?说简单点,就是能把重复的方法拆分到一个文件,通过 use 引入以达到代码复用的目的。主要的优点在于随意组合,耦合性低,可读性高。还有以下两个优点:
1-减少接口实现代码冗余: 假设不使用trait实现接口方法, 多个类扩展某个接口, 必须在这些类内部实现该接口的方法, 这会造成实现接口的代码冗余.
2-借用trait实现多继承: 假设两个(或多个)接口已经有对应的实现类, PHP的单继承限制, 没有办法同时继承这两个(或多个)实现类. 但使用trait实现接口, 就能实现多继承。
缺少项目实战经验,所以暂不是很清楚trait的缺点如何?
四、总结:对trait有了一个初步的认识,需在后面的实操中加强记忆和如何运用灵活。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号