批改状态:未批改
老师批语:
trait实例,实现代码复用
自 PHP 5.4.0 起,PHP 实现了一种代码复用的方法,称为 trait。
Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。
Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。
具体示例如下:
先创建一个动物类
<?php
/**
* Created by PhpStorm.
* User: John
* Date: 2018/5/9
* Time: 0:19
*/
class Dongwu
{
protected $types; //类型
//为属性初始化
public function __construct($types)
{
$this->types=$types;
}
//添加公共方法
public function Action()
{
return $this->types.'爬楼顶';
}
}
//创建 trait 在 trait 中可以访问父类中的属性
//在 trait 中如果方法名与父类相同,trait 中的会优先于父类中的
trait Gou
{
protected $type; //类型
//叫
public function Jiao($jiao)
{
'这个动物是:'.$this->types.'它的品种是:'.$this->type.'它正在'.$jiao;
}
//添加公共方法
public function Action()
{
return $this->types.'食屎。。';
}
}再建一个猫类继续到动物类:
<?php
/**
* Created by PhpStorm.
* User: John
* Date: 2018/5/9
* Time: 0:44
*/
class Mao extends Dongwu
{
//导入创建的 trait 类 , 如果 trait类中创建了静态的方法,那么在此继承类中必须要实现,否则会报错
use Gou;
}最后测试阶段:
<?php
/**
* Created by PhpStorm.
* User: John
* Date: 2018/5/9
* Time: 0:20
*/
//使用匿名函数自动加载类
spl_autoload_register(function ($className){
require 'class/'.$className.'.php';
});
$dongwu = new Dongwu('猫');
echo $dongwu->Action();
echo '<hr>';
//测试mao类中的方法,mao类中继续了Dongwu类,其中动物类中有普通类跟 trait 类
$mao = new Mao('狗');
//此方法 普通类跟 trait 中都相同,而调用的时候会声调用 trait 中的方法
echo $mao->Action();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号