批改状态:合格
老师批语:
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/5/8 0008
* Time: 10:23
* trait 是什么
* 1.trait是为了php单继承语言设计的代码复用机制
* 2.之前可以通过函数或类来实现代码复用
* 3.trait可以简单的理解为一个类的方法集合 工作在子类与父类之间 权重在子类和父类之间 同名方法优先级别是子类 trait类父类
* 4.不仅仅支持方法集合 还支持 抽象类和静态类
* 5.当前类会覆盖trait类 trait会覆盖同类名成员
* 6.trait不是类 不能实例化(抽象类和接口也不能实例化)
*
*/
//创建父类
class Books
{
protected $bookname;
public function __construct($bookname='php')
{
$this->bookname = $bookname;
}
public function reading($who){
return $who.'在图书馆,正在看'.$this->bookname.'这本书';
}
}
//创建trait类
trait Course
{
private $name = '张畅';
private $name1='庐阳';
public function palaygame(){
return $this->name.'正在上体育课';
}
// public function reading($who = 'lizhi'){
// return $who.'看电影';
// }
abstract static function dowork();
}
trait Lisen
{
//在所有的trait类中不允许有同名的属性名称 目前版本还没有处理同名机制
private $name2 = '刘丽婵';
// public function reading(){
// return $this->name2.'正在锻炼英语听力能力。';
// }
}
//创建子类
class student extends Books
{
//支持同时导入多个trait类
use Course,Lisen{
//在两个trait中有两个同名的方法好会产生冲突 所以采用insteadof(传递) 把方法指向某个trait中的方法
//在另外trait中命名新的方法名称 用于访问
// Course::reading insteadof Lisen;
// Lisen::reading as myreading;
}
//在子类中必须实现在trait类中声明的抽象静态类
public static function dowork($name)
{
return $name.':洗洗睡吧 明天还要上班';
}
// public function reading($who='我')
// {
// return $who.'正在不知疲倦的coding';
// }
}
//实例化 student
$student = new student();
//调用方法
echo $student->reading('冰刺');
//调用trait中重名的方法
//echo $student->myreading();
//调用静态方法
echo $student::dowork('小李');
echo student::dowork('老刘');
//调用trait类中的方法
echo $student->palaygame();点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号