批改状态:未批改
老师批语:
总结:
trait是为单继承语言量身定制的代码复用机制;
之前可以通过函数或类来实现代码复用;
trait可以简单的理解为一个类方法的集合,工作在父类与子类之间;
但是trait不仅仅局限于方法集合,还支持抽象,静态与属性;
当前类成员会覆盖trait类成员,而trait中的成员,又可以覆盖同名类成员
重要提示:trait不是类,不能实例化,
<?php
if (!class_exists('Person')) {
class Person
{
protected $name;
public function _construct($name='小明')
{
$this->name = $name;
}
public function study($course='php')
{
return $this->name.'在学习'.$course;
}
}
}
class Coures
{
//trait 也可以有自己的属性
public $friend='小花';
public function sport($name='打篮球')
{
return $this->name .'和'.$this->friend.'学习'.$name ;
}
//抽象静态方法
abstract public static function hobby($name);
//和person同类方法
public function study($course='ajax')
{
return $this->friend.'在学习'.$course;
}
}
//有了父类,还有一个trait类 再创建一个子类
class Student extends Person
{
//导入tarit类
use Coures;
protected $name='小军';
public static function hobby($name)
{
return $name;
}
public function study($course='html')
{
return $this->name.'在学习'.$course;
}
}
//实例化Student
$student = new Student();
echo $student->study();点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号