批改状态:合格
老师批语:
/**
* trait是什么?
* 1.trait是为了单继承语言量身定做的代码复用机制
* 2.trait简单理解为一个方法集合
*/
父类:汽车car类,中有一个显示车速度的方法
class Car
{
protected $name;
public function __construct($name='五菱宏光') {
$this->name = $name;
}
public function sport($speace){
return $this->name.'的车速为'.$speace;
}
}点击 "运行实例" 按钮查看在线实例
定义一个trait类扩展car类的方法
trait Course{
public $speace;
//和Car类同名的方法
public function sport($speace='200'){
return $this->name.'的车速'.$speace.'英里';
}
}点击 "运行实例" 按钮查看在线实例
子类Orther
//有了一个父类,还有一个trait类
class Other extends Car{
//导入trait类
use Course;
}
//实例化Student
$other = new Other ('东风');
echo $other ->sport(300);点击 "运行实例" 按钮查看在线实例
返回值为:
东风的车速为300英里
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号