Home  >  Article  >  Backend Development  >  How to implement multiple inheritance in php

How to implement multiple inheritance in php

(*-*)浩
(*-*)浩Original
2019-09-04 15:11:223260browse

php implements multiple inheritance-trait syntax

How to implement multiple inheritance in php

##Since PHP 5.4.0, PHP implements a code Reused methods are called traits.


Trait is a code reuse mechanism prepared for single inheritance languages ​​like PHP. Traits are designed to reduce the limitations of single-inheritance languages ​​and allow developers to freely reuse methods in independent classes within different hierarchies. The semantics of Trait and Class composition define a way to reduce complexity and avoid the typical problems associated with traditional multiple inheritance and Mixin classes.

Trait is similar to Class, but is only designed to combine functionality in a fine-grained and consistent way. Cannot be instantiated through the trait itself. It adds a combination of horizontal features to traditional inheritance; that is, there is no need for inheritance between several Classes in an application. (Recommended learning:

PHP Video Tutorial)

Members inherited from the base class will be overridden by members inserted by the trait. The order of precedence is that members from the current class override the trait's methods, and the trait overrides the inherited methods.

The following is the code:

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/>

The output is:

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

The above is the detailed content of How to implement multiple inheritance in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn