然则开辟中用到多继续该怎样办呢?
下面引见一下运用trait来完成php中多继续的题目。(引荐进修:PHP视频教程)
自PHP5.4最先,php完成了代码复用的要领trait语法。
Trait是为PHP的单继续言语而预备的一种代码复用机制。为了削减单继续的限定,是开辟在差别构造条理上去复用method,Trait 和 Class 组合的语义定义了一种削减复杂性的体式格局,防止传统多继续和 Mixin 类相干典范题目。
须要注重的是,从基类继续的成员会被 trait 插进去的成员所掩盖。优先递次是来自当前类的成员掩盖了 trait 的要领,而 trait 则掩盖了被继续的要领。
先来个例子:
trait TestOne{ public function test() { echo "This is trait one <br/>"; } } trait TestTwo{ public function test() { echo "This is trait two <br/>"; } public function testTwoDemo() { echo "This is trait two_1"; } } class BasicTest{ public function test(){ echo "hello world\n"; } } class MyCode extends BasicTest{ //假如纯真的直接引入,两个类中涌现雷同的要领php会报失足 //Trait method test has not been applied, because there are collisions with other trait //methods on MyCode //use TestOne,TestTwo; //怎样处置惩罚上面所涌现的毛病呢,我们只需运用insteadof关键字来解决要领的争执 use TestOne,TestTwo{ TestTwo::test insteadof TestOne; } } $test = new MyCode(); $test->test(); $test->testTwoDemo();
运转效果:
This is trait two This is trait two_1
以上就是php能继续多个父类吗的细致内容,更多请关注ki4网别的相干文章!