批改状态:合格
老师批语:
写一个trait实例,实现代码复用:
1.源码如下:
<?php
/**
* 学生类申明
*/
if (!class_exists('Student'))
{
class Student
{
protected $id;//学号
protected $name;//姓名
public function __construct($name='张三')
{
$this->name=$name;
}
public function study($course='语文')
{
return $this->name.'在学习'.$course;
}
}
}
if(!trait_exists('Course')){
trait Course
{
public $num=13;//课程数
public function study($course='数学')
{
return $this->name.'在学习'.$course;
}
}
}
if(!trait_exists('Sport')){
trait Sport
{
public $sport='踢足球';
public function sport($sport='打篮球')
{
return $this->name.'会'.$sport;
}
}
}
class Member extends Student
{
use Course,Sport{}
public function study($course = '英语')
{
parent::study($course);
return $this->name.'在学习'.$course;
}
}
$member = new Member();
//1.访问父类Person中的方法
echo $member->study();
echo '<hr>';
//
////2.访问trait类中的方法
echo $member->sport();
//
echo '<hr>';
//
//
//3.当trait中存在与父类同名方法时,trait优先级要高,当子类中存在与trait类同名方法时,子类优先级要高
echo $member->study();
//4.子类可以从多个trait中获取方法集
//
echo '<hr>';
echo $member->sport();点击 "运行实例" 按钮查看在线实例
2.运行结果:

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号