PHP 中的魔术方法——方法重载

方法重载

 __call()当对一个对象未定义的实例方法进行调用(访问)的时候,会自动调用预先定义好的魔术方法:__call()

 

   __callstatic()当对一个类未定义的静态方法进行调用(访问)的时候,会自动调用预先定义好的静态魔术方法:__callstatic()

 

Demo:

 1  class Test{
 2         function f(){
 3             echo "<br>在";
 4         }
 5 
 6         //需要两个参数
 7         //$fun_name:不存在的方法名
 8         //$fun_arg:调用该不存在的方法时的所有实参--它是一个数组
 9         function __call($fun_name,$fun_arg){
10             //echo "<br>调用不存在的普通实例方法";
11             $count = count($fun_arg);
12             if($fun_name == "do"){
13                 if($count == 1){
14                     $this->pa($fun_arg[0]);
15                 }elseif($count == 3){
16                     $this->papa($fun_arg[0],$fun_arg[1],$fun_arg[2]);
17                 }else{
18                     echo "<br>MM:不要对我使用套路";
19                 }
20 
21             }else{
22                 echo "<br>请勿打扰";
23             }
24         }
25         function pa($pa){
26             echo "<br>GG:{$pa}";
27             echo "<br>MM:叔叔,我们不约";
28         }
29         function papa($pa1,$pa2,$pa3){
30             echo "<br>MM:泡妞七字真言";
31             echo "<br>GG:{$pa1}{$pa2}{$pa3}";
32         }
33 
34         static function __callstatic($fun_name,$fun_arg){
35             if($fun_name == "staticdo"){
36                 self::staticpa();
37             }
38         }
39         static function staticpa(){
40             echo "<br>MM:gun~";
41         }
42     }
43     $t = new Test();
44     $t->f(); //调用存在的方法
45     $t->f2();  //调用不存在的方法
46     $t->do("约吗");
47     $t->do("吃饭","看电影");
48     $t->do("胆大","心细","脸皮厚");
49     Test::staticdo();
View Code
原文地址:https://www.cnblogs.com/godLike7/p/6808850.html