Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。
Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。
<?php/** trait实现了代码的复用* 并且突破了单继承的限制* trait是为不是类,不能实例化*/trait Demo1{public function hello1(){return __METHOD__;}}trait Demo2{public function hello2(){return __METHOD__;}}class Demo{use Demo1,Demo2;public function hello(){return __METHOD__;}public function test1(){return $this->hell1();}public function test2(){return $this->hell2();}}$obj = new Demo;echo $obj->hello();echo '<hr>';echo $obj->test1();echo '<hr>';echo $obj->test2();
<?php/** trait 优先级的问题* 1. 当前类中的方法与train类,父类中的方法重名了,怎么办?* 2. 优先级: 当前类 > 引用的train类 > 父类*/trait Demo1{public function hello(){return __METHOD__;}}trait Demo2{public function hello2(){return __METHOD__;}}class Test{public function hello(){return __METHOD__;}}class Demo extends Test{use Demo1,Demo2;public function hello(){return __METHOD__;}public function test1(){return $this->hell1();}public function test2(){return $this->hell2();}}$obj = new Demo;echo $obj->hello();//echo '<hr>';//echo $obj->test1();//echo '<hr>';//echo $obj->test2();
<?php/** trait 优生级的问题* 1. 当前类中的方法与train类,父类中的方法重名了,怎么办?* 2. 优先级: 当前类 > 引用的train类 > 父类* 3. 多个 train类中的方法重名了,怎么办?*/trait Demo1{public function hello(){return __METHOD__;}}trait Demo2{public function hello(){return __METHOD__;}}class Test{public function hello(){return __METHOD__;}}class Demo extends Test{use Demo1,Demo2{Demo1::hello insteadof Demo2;Demo2::hello as Demo2Hello;}// public function hello()// {// return __METHOD__;// }public function test1(){return $this->hell1();}public function test2(){return $this->Demo2Hello();}}$obj = new Demo;echo $obj->hello();//echo '<hr>';//echo $obj->test1();echo '<hr>';echo $obj->test2();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号