PHP 实现了一种代码复用的方法,称为 trait。
Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。
Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。
* 给类动态添加新方法
* @author fantasy
trait DynamicTrait {
* 自动调用类中存在的方法
public
function
__call(
$name
,
$args
) {
if
(
is_callable
(
$this
->
$name
)){
return
call_user_func
(
$this
->
$name
,
$args
);
}
else
{
throw
new
\RuntimeException("Method {
$name
} does not exist"
);
* 添加方法
public
function
__set(
$name
,
$value
) {
$this
->
$name
=
is_callable
(
$value
)?
$value
->bindTo(
$this
,
$this
):
$value
;
* 只带属性不带方法动物类
* @author fantasy
class
Animal {
use
DynamicTrait;
private
$dog
= '汪汪队'
;
$animal
=
new
Animal;
//
往动物类实例中添加一个方法获取实例的私有属性$dog
$animal
->getdog =
function
() {
return
$this
->
dog;
echo
$animal
->getdog();
//
输出 汪汪队
代码复用到其他地方 use一下就行, 多个用,分开
转 : https://www.php.net/manual/zh/language.oop5.traits.php