php中__call() 和 __callStatic方法的使用


__call 與__callStatic 魔法方法是php5.3后新增的,二者的應用場景:

1、當要調用的方法不存在或權限不足時,會自動調用__call 方法。

2、當調用的靜態方法不存在或權限不足時,會自動調用__callStatic方法。

 

class Person
{

    public function __call($method, $arguments) {
        echo '我是要調用的不存在的動態方法名: ', $method, '<br>';
        echo '以下是通過__call方法顯示的參數', '<br>';
        var_dump($arguments);
    }

     public static function __callStatic($method, $arguments) {
        echo '我是要調用的不存在的靜態方法名: ', $method, '<br>';
        echo '以下是通過__callStatic方法顯示的參數', '<br>';
        var_dump($arguments);
     }
}

// 調用對象不存在的方法hello
(new Person())->hello(['a', 'b'], ['c', 'd']);
echo '<hr>';
// 調用類不存在的靜態方法world
Person::world(['e', 'f'], ['g', 'h']);

輸出如下:

我是要調用的不存在的動態方法名: hello
以下是通過__call方法顯示的參數
D:\wamp64\www\test\call.php:9:
array (size=2)
  0 => 
    array (size=2)
      0 => string 'a' (length=1)
      1 => string 'b' (length=1)
  1 => 
    array (size=2)
      0 => string 'c' (length=1)
      1 => string 'd' (length=1)
我是要調用的不存在的靜態方法名: world
以下是通過__callStatic方法顯示的參數
D:\wamp64\www\test\call.php:15:
array (size=2)
  0 => 
    array (size=2)
      0 => string 'e' (length=1)
      1 => string 'f' (length=1)
  1 => 
    array (size=2)
      0 => string 'g' (length=1)
      1 => string 'h' (length=1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM