当前位置:首页 > PHP教程 > php应用 > 列表

php 使用 __call实现重载功能示例

发布:smiling 来源: PHP粉丝网  添加日期:2022-01-22 21:44:44 浏览: 评论:0 

这篇文章主要介绍了php 使用 __call实现重载功能,结合实例形式分析了PHP使用__call实现重载的相关操作技巧,需要的朋友可以参考下。

本文实例讲述了php 使用 __call实现重载功能,分享给大家供大家参考,具体如下:

  1. <?php 
  2. /** 
  3.  * Created by PhpStorm. 
  4.  * User: funco 
  5.  * Date: 17-6-9 
  6.  * Time: 下午1:39 
  7.  */ 
  8. class MulStat 
  9. { 
  10.   // showClass 可以接受0个参数 
  11.   private function showClass() { 
  12.     echo "this is class ".__CLASS__; 
  13.   } 
  14.  
  15.   // showString 可以接受一个参数 
  16.   private function showString($str) { 
  17.     echo "string is ".$str; 
  18.   } 
  19.  
  20.   // __call方法 可以获取实例化对象调用的成员函数名和向该被调函数传递的参数个数 
  21.   public function __call($name, $args) { 
  22.     // 先判断要调用的函数名$name 
  23.     if($name == "showInfo"){ 
  24.       // 然后可以根据参数($args)数量判断调用哪个成员函数 
  25.       switch(count($args)) {           // count可以计算数组元素个数 
  26.         case 0: 
  27.           $this->showClass();break; 
  28.         case 1: 
  29.           $this->showString($args[0]);break; 
  30.       }// switch 
  31.     }// if 
  32.   } 
  33. } 
  34.  
  35. //实例化MulStat类 
  36. $mulStat = new MulStat(); 
  37.  
  38. echo "\$mulStat->showInfo(\"funco 小风\"):\n"; 
  39. $mulStat->showInfo("funco 小风"); 
  40.  
  41. // 两次换行 便于观察结果 
  42. echo "\n\n"; 
  43.  
  44. echo "\$mulStat->showInfo():\n"; 
  45. $mulStat->showInfo(); 

运行结果:

$mulStat->showInfo("funco 小风"):

string is funco 小风

$mulStat->showInfo():

this is class MulStat

Tags: __call php重载

分享到: