Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:trait虽好,也不可滥用
关键字:insteadOf 替换; as 取别名或者修改权限;
实例演示:
<?php
trait tUser1
{
public function res()
{
return __TRAIT__.'=>'.__METHOD__;
}
}
trait tUser2
{
public function res()
{
return __TRAIT__.'=>'.__METHOD__;
}
}
trait tUser3
{
use tUser1,tUser2
{
tUser1::res insteadOf tUser2;//替换 tUser2 里面的res方法
tUser2::res as res2;//给res 取一个别名
}
use tUser1{res as protected res1;}//修改tUser 方法的访问权限
}
class User
{
use tUser3;
}
$obj=new User();
echo $obj->res();
echo '<hr>';
echo $obj->res2();
echo '<hr>';
echo $obj->res1();
?>
输出结果:
实例演示:
<?php
interface iUser1
{
const NAME='刘德华';
const AGE=17;
public static function res();
public static function ret($age2);
}
trait tUser1
{
public static function res()
{
return iUser1::NAME.iUser1::AGE.'出道';
}
}
abstract class tUser2 implements iUser1
{
// use tUser1;
public static function ret($age2)
{
// $age2=24;
return $age2.'获取金像奖';
}
}
class User extends tUser2
{
Use tUser1;
}
$obj=new User();
echo $obj::res();
echo '<hr>';
echo $obj::ret(24);
?>
输出结果:
个人总结:接口中声明方法;需要实现直接在抽象类或者trait类中实现,工作类中直接调用就好,注意引入的关系和层级