Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:能理解就很好, 毕竟刚刚接触
<?php
//trait组合实现功能扩展
trait tTime
{
protected function getTime()
{
//获取当前日期时间并返回
return date("Y-m-d");
}
}
trait tWork
{
protected $worker = '学习trait';
protected function getWork()
{
//获取当前工作并返回
return $this->worker;
}
}
trait tToday
{
//引入trait
use tTime, tWork;
protected $name = '小周';
protected $day = '1';
}
class Today
{
use tToday;
public $ku = '其它什么都没做';
public function say()
{
//返回创建与引入的值
return $this->name . '在' . $this->getTime() . '花费' . $this->day . '天时间来' . $this->getWork(). ',' . $this->ku;
}
}
//客户端代码
$work = new Today();
echo $work->say();
<?php
//trait中相同方法与替代
trait tTime
{
protected function getTime()
{
//获取当前日期时间并返回
return '现在的时间是'.date("Y-m-d H:i:s");
}
}
trait tWork
{
protected $worker = '学习trait';
protected function getWork()
{
//获取当前工作并返回
return $this->worker;
}
}
trait tWorks
{
protected $workers = '玩耍';
protected function getWork()
{
//获取当前工作并返回
return $this->workers;
}
}
trait tToday
{
//引入trait
use tTime, tWork, tWorks {
//1.替代
tWork::getWork insteadof tWorks;
//2.别名
tWorks::getWork as tTodays;
}
//as:还可以修改trait成员的访问控制
use tWork {getWork as public tWorkss;}
protected $name = '小周';
protected $day = '1';
}
class Today
{
use tToday;
public $ku = '其它什么都没做';
public function say()
{
//返回创建与引入的值
return $this->name . '在' . $this->getTime() . '花费' . $this->day . '天时间来' . $this->tTodays(). ',' . $this->ku;
}
}
//客户端代码
$work = new Today();
echo $work->say();
echo '<br>';
echo $work->tWorkss();
<?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("Y-m-d H:i:s");
}
}
}
//实现这个类
if (!class_exists('Work')){
class Work implements iTime
{
use tTime;
}
}
echo Work::index();
理解是能理解,也想搞一个实例,但是现在头脑里没有那个概念