Home > Backend Development > PHP Tutorial > PHP study notes--the use of traits (generated to achieve multiple inheritance)

PHP study notes--the use of traits (generated to achieve multiple inheritance)

PHP中文网
Release: 2016-07-30 13:31:25
Original
999 people have browsed it


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
Copy after login

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}
}
Copy after login


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 (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template