首页  >  文章  >  后端开发  >  php怎么实现多继承

php怎么实现多继承

(*-*)浩
(*-*)浩原创
2019-09-04 15:11:223216浏览

php实现多继承-trait语法

php怎么实现多继承

自PHP 5.4.0起,PHP实现了一种代码复用的方法,称为trait。

Trait是为类似PHP的单继承语言而准备的一种代码复用机制。Trait为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。

Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。(推荐学习:PHP视频教程

从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。

以下为代码:

trait traitTestOne{<br/>    public function test(){<br/>        echo "This is trait one <br/>";<br/>    }<br/>    public function testOne(){<br/>        echo "one <br/>";<br/>    }<br/>}<br/> <br/>trait traitTestTwo{<br/>//  public function test(){<br/>//      echo "This is trait two";<br/>//  }<br/>    public function testTwo(){<br/>        echo "two <br/>";<br/>    }<br/>}<br/> <br/>class basicTest{<br/>    public function test(){<br/>        echo "hello world\n";<br/>    }<br/>}<br/>class myCode extends basicTest{<br/>    use traitTestOne,traitTestTwo;<br/>}<br/> <br/>$test = new mycode();<br/>$test->test();<br/>$test->testOne();<br/>$test->testTwo();<br/>

输出为:   

This is trait one<br/>one<br/>two<br/>

以上是php怎么实现多继承的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn