Trait组合的同名方法的命名冲突的解决方案
trait tBase1
{
protected static $name;
public function display()
{
return __TRAIT__;
}
}
trait tBase2
{
protected static $price;
public function display()
{
return __TRAIT__;
}
}
trait tBase
{
use tBase1,tBase2{
//1.当trait中方法重名时可以替换
tBase1::display insteadOf tBase2;
//2.给方法取别名
tBase2::display as td2;
}
//as还能改访问限制
use tBase1 {display as protected;}
}
class Product
{
use tBase;
public static function write($name,$price)
{
echo self::$name= $name .'的价格是:'.self::$price=$price.__METHOD__;
}
public static function fatch($name,$price)
{
return static::write($name,$price);
}
}
class Base extends Product
{
public static function write($name,$price)
{
echo self::$name= $name .'优惠后的价格是:'.self::$price=$price.__METHOD__;
}
}
Base::fatch('手机',8888);
$product = new Product;
echo $product->display();
图例
$trait 实现 接口方法的优点
1.可以更方便的应用在工作类当中
2.客户端代码越简洁越好 容易维护
小抽奖
interface iReward
{
public function getReward($total);
}
trait tReward
{
public function getReward($total)
{
$win1 = floor((0.12*$total)/100);
$win2 = floor((1*$total)/100);
$win3 = floor((2*$total)/100);
$other = $total-$win1-$win2-$win3;
$return = [];
for ($i=0;$i<$win1;$i++)
{
$return[] = 1;
}
for ($j=0;$j<$win2;$j++)
{
$return[] = 2;
}
for ($m=0;$m<$win3;$m++)
{
$return[] = 3;
}
for ($n=0;$n<$other;$n++)
{
$return[] = '谢谢惠顾';
}
shuffle($return);
return $return[array_rand($return)];
}
}
class Reward implements iReward{
use tReward;
}
$reward =new Reward;
echo $reward->getReward(1000);
总结
这节课学习了trait的组合命名冲突的2种解决方法,as的用法,以及接口与trait的实战,发现自己的数组函数基础很不好,需要多复习。