欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP的Trait機制原理與用法分析

 更新時間:2019年10月18日 10:36:07   作者:學知無涯  
這篇文章主要介紹了PHP的Trait機制原理與用法,結合實例形式分析了PHP Trait機制的基本功能、原理及簡單使用技巧,需要的朋友可以參考下

本文實例講述了PHP的Trait機制原理與用法。分享給大家供大家參考,具體如下:

Trait介紹:

1、自PHP5.4起,PHP實現(xiàn)了一種代碼復用的方法,稱為trait。
2、Trait是為類似PHP的單繼承語言二準備的一種代碼復用機制。
3、Trait為了減少單繼承語言的限制,使開發(fā)人員能夠自由地在不同層次結構內(nèi)獨立的類中復用method。
4、trait實現(xiàn)了代碼的復用,突破了單繼承的限制;
5、trait是類,但是不能實例化。
6、當類中方法重名時,優(yōu)先級,當前類>trait>父類;
7、當多個trait類的方法重名時,需要指定訪問哪一個,給其它的方法起別名。

示例:

trait Demo1{
 public function hello1(){
  return __METHOD__;
 }
}
trait Demo2{
 public function hello2(){
  return __METHOD__;
 }
}
class Demo{
 use Demo1,Demo2;//繼承Demo1和Demo2
 public function hello(){
  return __METHOD__;
 }
 public function test1(){
  //調(diào)用Demo1的方法
  return $this->hello1();
 }
 public function test2(){
  //調(diào)用Demo2的方法
  return $this->hello2();
 }
}
$cls = new Demo();
echo $cls->hello();
echo "
"; echo $cls->test1(); echo "
"; echo $cls->test2();

運行結果:

Demo::hello
Demo1::hello1
Demo2::hello2

多個trait方法重名:

trait Demo1{
 public function test(){
  return __METHOD__;
 }
}
trait Demo2{
 public function test(){
  return __METHOD__;
 }
}
class Demo{
 use Demo1,Demo2{
  //Demo1的hello替換Demo2的hello方法
  Demo1::test insteadof Demo2;
  //Demo2的hello起別名
  Demo2::test as Demo2test;
 }
 public function test1(){
  //調(diào)用Demo1的方法
  return $this->test();
 }
 public function test2(){
  //調(diào)用Demo2的方法
  return $this->Demo2test();
 }
}
$cls = new Demo();
echo $cls->test1();
echo "
"; echo $cls->test2();

運行結果:

Demo1::test
Demo2::test

更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家PHP程序設計有所幫助。

相關文章

最新評論