trait is a new feature of php5.4 that is created to achieve multiple inheritance.
The method of use is as follows:
<?phptrait Tool{functiongetName(){echo"tool name"; } }classHammerTool{useTool} $tempTool = newHammerTool();$tempTool->getName();//输出:tool name
The priority is that the subclass overrides the trait, and the trait overrides the parent class inherited by the subclass.
If you use several traits and there are the same methods in the traits, you can use the insteadof or as method to replace or rename them.
For example:
<?phptrait A{functionsmallTalk(){echo"A smallTalk"; }functionbigTalk(){echo"A bigTalk"; } }trait B{functionsmallTalk(){echo"B smallTalk"; }functionbigTalk(){echo"B bigTalk"; }functionmiddleTalk(){echo"B middleTalk"; } }classTalker {useA, B {B::smallTalkinsteadofA;//用B的smallTalk替换A的方法。A::bigTalk insteadof B; B::middleTalk asprivate myPrivateHello;//重命名为B} }
Copyright statement: This article is an original article. Reprints must indicate the source. The views in the article only represent the views at the time. There must be shortcomings. Welcome to remind me. Thank you very much!
The above introduces the PHP study notes - the use of traits (generated to achieve multiple inheritance), including aspects of content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!