//命名冲突和改变访问控制
trait t8{
public function say(){
echo 'these are two method with the same name.';
}
}
trait t9{
protected function say(){
echo 'these are two method with the same name.';
}
}
trait t10{
use t8,t9{
t8::say insteadof t9;
t9::say as public read;
}
}
class work3{
use t10;
}
$work3=new work3();
echo $work3->say().'<br>';
echo $work3->read().'<br>';
//trait和interface及class
trait t11{
public function aa($year){
$age=2020-$year;
return $age;
}
}
interface i2{
const NAME='jack';
public function caculator(int $i);
}
class Work4 implements i2{
use t11;
public function caculator(int $i){
if($i>0){
$sum=0;
for($j=0;$j<=$i;$j++){
$sum=$sum+$j;
}
return $sum;
}else {
return '参数非法';
}
}
}
$work4=new Work4();
echo '参数年份,计算年龄:<br>';
echo $work4::NAME.'的年龄是:'.$work4->aa(2000).'<br>';
echo '参数正整数,进行累加:<br>';
echo '结果是'.$work4->caculator(10).'<br>';
//trait的理解:一些方法和常量打包在trait里面,在类中使用时,use一下就能用,
//优点:省去了父类/子类和继承,以及访问控制这些麻烦(trait中都是public);
//缺点:a.方法都是public,不能访问限制;b.由于trait可以use trait,层数多了可能会把我搞晕吧!