Home  >  Article  >  Backend Development  >  PHP Trait function and usage example analysis

PHP Trait function and usage example analysis

coldplay.xixi
coldplay.xixiforward
2020-07-15 17:30:171971browse

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 "<br/>";
$people->say();
echo "<br/>";
$people->eatbak();

Running result:

A-eat
B-say
B-eat

2. Modify access control

<?php
trait Test {
 public function say() {
  echo &#39;say hello&#39;;
 }
}
 
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!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete