1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php /** * 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->hello1(); } public function test2(){ return $this->hello2(); } } $demo = new demo(); echo $demo->hello(); //demo::hello echo '<hr>'; echo $demo->test1(); //demo1::hello1 echo '<hr>'; echo $demo->test2(); //demo2::hello2 ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php /** * trait 优先级的问题 * 当前类的方法跟trait类 父类 重名 优先级 * 本类方法优先级 高于trait类 * trait类的方法 优先级 高于父类 * 总结:优先级顺序 本类 => Trait类 => 父类 */ /** * Trait 类 我的优先级 在于父类之前 本类之后 */ Trait demo1{ public function hello(){ return __METHOD__; } } /** * 父类 我的优先级最低 */ class Test{ public function hello(){ return __METHOD__; } } /** * 本类 优先级最高 */ class demo extends Test{ //把代码的方法拿进来 当前类就可以直接调用 复用 use demo1; public function hello(){ return __METHOD__; } } $demo = new demo(); echo $demo->hello(); ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<?php /** * 当Trait 类存在多个同名方法的时候 */ /** * 我有hello方法 */ Trait Demo1{ public function hello(){ return __METHOD__; } } /** * 我有hello方法 */ Trait Demo2{ public function hello(){ return __METHOD__; } } /** * 我有hello方法 */ 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->hello1(); } public function test2(){ return $this->Demo2Hello(); } } $demo = new demo(); echo $demo->hello(); //本类有hello方法 优先级最高 输出没问题 // /** * 注释掉本类的hello方法 报错存在 Trait类方法 冲突 * 加规则 demo1的hello方法替换掉 demo2的hello方法 */ // use Demo1,Demo2{ // Demo1::hello insteadof Demo2; //替换掉demo2 // Demo2::hello as Demo2Hello; //demo2 设置别名 // } ?> |

我的微信
把最实用的经验,分享给最需要的读者,希望每一位来访的朋友都能有所收获!