PHP 魔術方法 __call 與 __callStatic 方法


PHP 魔術方法 __call 與 __callStatic 方法

PHP 5.3 后新增了 __call 與 __callStatic 魔法方法。

  • __call 當要調用的方法不存在或權限不足時,會自動調用__call 方法。
  • __callStatic 當調用的靜態方法不存在或權限不足時,會自動調用__callStatic方法。
class Animal
{
    private function eat()
    {
        echo 'eat';
    }

    public function __call($name, $arguments)
    {
        echo '調用不存在的方法名是:' . $name . '<br>參數是:';
        print_r($arguments);
        echo '<br>';
    }

    public static function __callStatic($name, $arguments)
    {
        echo '調用不存在的--靜態--方法名是:' . $name . '<br>參數是:';
        print_r($arguments);
    }
}

$animal = new Animal();
$animal->drink([1, 2, 3]);
// 調用不存在的方法名是:drink
// 參數是:Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) )

Animal::smile(['可愛', '大笑', '微笑']);
// 調用不存在的--靜態--方法名是:smile
// 參數是:Array ( [0] => Array ( [0] => 可愛 [1] => 大笑 [2] => 微笑 ) )

這里說一下我看到的 __callStatic 應用場景

擴展類中的方法 在tp5框架 Log.php 中

 /**
     * 靜態調用
     * @param $method
     * @param $args
     * @return mixed
     */
    public static function __callStatic($method, $args)
    {
        // 類變量$type = ['log', 'error', 'info', 'sql', 'notice', 'alert', 'debug'];
        if (in_array($method, self::$type)) {
            array_push($args, $method);
            return call_user_func_array('\\think\\Log::record', $args);
        }
    }

這樣就可以擴展出 Log::log()、Log::error()...等7個方法

還有一種用法,可以看 tp5 框架 Db.php 文件最下面,** 可以調用其他類的方法 **

   // 調用驅動類的方法
    public static function __callStatic($method, $params)
    {
        // 自動初始化數據庫
        return call_user_func_array([self::connect(), $method], $params);
    }

今天看到監聽 sql 代碼的時候,發現 \think\Db 下面沒有 listen 方法,當我們調用\think\Db::listen 的時候,實際調用的是 Connection 類中的 listen 方法

上述代碼 self::connect() 返回的是一個連接對象,$method 是這個對象中的方法,構成 call_user_func_array([對象,方法],參數)

順便附上 call_user_func_array 這個函數的使用文檔

菜鳥一枚,如有不對,敬請指出


免責聲明!

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



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