PHP Trait function and usage example analysis

coldplay.xixi
Release: 2023-04-09 08:24:01
forward
1827 people have browsed it

PHP Trait function and usage example analysis

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.

1. If the introduced Trait has a method with the same name

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 "
"; $people->say(); echo "
"; $people->eatbak();
Copy after login

Running result:

A-eat
B-say
B-eat

2. Modify access control

say();
Copy after login

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!

Related labels:
source:jb51.net
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!