Trait 是用来完成代码复用的,他突破了PHP只能单继承的局限,它具有类的大部分特点,唯独不可以被实例化(new)
use 可以在一个类中引入Trait
Trait 在使用时的优先级 子类 > Trait > 父类
如何在一个类中引入多个Trait,而且Trait中的方法命名冲突时,可以使用 insteadof 来设置谁生效。也可以给另一个起别名 as 。
Trait Demo1{
publick function hello1(){
return __METHOD__;
}
}
Trait Demo2{
publick function hello1(){
return __METHOD__;
}
}
class Demo{
use Demo1,Demo2{
Demo1::hello1 insteadof Demo2;
Demo2::hello1 as Demo2Hello1;
};
publick function hello(){
return __METHOD__;
}
}
$a = new Demo()
$a -> hello()
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号