PHP 魔術方法之 __call 與 __callStatic
- PHP
- 魔術方法
__call 方法的使用
定義:在對象中調用一個不可訪問方法時,__call() 會被調用。
示例:
<?php
/**
* __call 測試
* @author [email protected]
*/
class Test {
public function __construct() {
}
public function show() {
echo "show 一下\n";
}
public function __call($method, $arguments) {
echo "不可訪問的方法都來我這裏了\n";
}
}
$test = new Test();
$test->show();//輸出: show 一下
$test->close(); //輸出: 不可訪問的方法都來我這裏來了
上面例子中調用 close 方法時不存在,所以被 __call 接收了。
但是如果調用類裏面的方法是 protected 或者是 private 的時候,是否可以被 __call 接收呢?
<?php
/**
* __call 測試
* @author [email protected]
*/
class Test {
public function __construct() {
echo "我是構造方法\n";
}
public function show() {
echo "show 一下\n";
}
public function __call($method, $arguments) {
echo "不可訪問的方法都來我這裏了\n";
}
protected function _sing() {
echo "我是唱歌的";
}
private function _run() {
echo "我是跑步的";
}
}
$test = new Test();
$test->show(); //輸出:show 一下
$test->_sing(); //輸出:不可訪問的方法都來我這裏了
$test->_run(); //輸出:不可訪問的方法都來我這裏了
$test->close(); //輸出:不可訪問的方法都來我這裏了
事實證明除了沒有定義的方法以及 private 和 protected 方法都會被魔術方法 __call 接收,所以定義爲調用一個不可訪問的方法時才被調用是十分準確的。(之前聽有些人說是當訪問一個未被定義的方法時被調用這是不準確的)
注意:__call 在使用時必須聲明爲 public 並且,方法必須有帶兩個參數,一個是 被調用的方法名,一個是方法攜帶的參數。
__callStatic 方法的使用
定義:用靜態方式中調用一個不可訪問方法時,__callStatic() 會被調用。
示例:
<?php
/**
* __callStatic 測試
* @author [email protected]
*/
class Test {
public function __construct() {
}
public static function show() {
echo "show 一下\n";
}
public static function __callStatic($className, $arguments) {
echo "不可訪問的靜態方法來這裏吧";
}
}
Test::show(); //輸出:show 一下
Test::close(); //輸出:不可訪問的靜態方法來這裏吧
同樣對於沒有定義的方法以及 private 和 protected 的靜態方法,都會被__callStatic 接收。