The examples in this article describe the functions and usage of PHP Trait. Share it with everyone for your reference, the details are as follows:
Trait is a code reuse mechanism prepared for single inheritance languages like PHP.
trait A{ public function eat(){ echo 'A-eat'; } public function say(){ echo 'A-say'; } } trait B{ public function eat(){ echo 'B-eat'; } public function say(){ echo 'B-say'; } } class People{ use A,B{ A::eat insteadof B; B::eat as eatbak; B::say insteadof A; } } $people = new People(); $people->eat(); echo "<br/>"; $people->say(); echo "<br/>"; $people->eatbak();
Running result:
A-eat
B-say
B-eat
<?php trait Test { public function say() { echo 'say hello'; } } class People { use Test { say as protected; } } $people = new People(); $people->say();
Running result:
Fatal error: Call to protected method People::say() from context '' in D:\phpdemo\trait_Demo.php on line 14
Related learning recommendations: PHP programming from entry to proficiency
The above is the detailed content of PHP Trait function and usage example analysis. For more information, please follow other related articles on the PHP Chinese website!