php 使用 __call重載

<?php  
  
/** 
 * Created by PhpStorm. 
 * User: funco 
 * Date: 17-6-9 
 * Time: 下午1:39 
 */  
class MulStat  
{  
    // showClass 可以接受0個參數  
    private function showClass() {  
        echo "this is class ".__CLASS__;  
    }  
  
    // showString 可以接受一個參數  
    private function showString($str) {  
        echo "string is ".$str;  
    }  
  
    // __call方法 可以獲取實例化對象調用的成員函數名和向該被調函數傳遞的參數個數  
    public function __call($name, $args) {  
        // 先判斷要調用的函數名$name  
        if($name == "showInfo"){  
            // 然後可以根據參數($args)數量判斷調用哪個成員函數  
            switch(count($args)) {                      // count可以計算數組元素個數  
                case 0:  
                    $this->showClass();break;  
                case 1:  
                    $this->showString($args[0]);break;  
            }// switch  
        }// if  
    }  
}  
  
//實例化MulStat類  
$mulStat = new MulStat();  
  
echo "\$mulStat->showInfo(\"funco 小風\"):\n";  
$mulStat->showInfo("funco 小風");  
  
// 兩次換行 便於觀察結果  
echo "\n\n";  
  
echo "\$mulStat->showInfo():\n";  
$mulStat->showInfo();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章