日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 默认站点!

默认站点

當前位置: 首頁 >

php 静态方法 call,php的 __callStatic 函数

發布時間:2023/12/2 28 豆豆
默认站点 收集整理的這篇文章主要介紹了 php 静态方法 call,php的 __callStatic 函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

現在很多框架中調用方法都是Foo::bar()這種格式的,但是他們真的是靜態方法嗎?

這種情況在 larave 中尤其常見,但是開發過程中很明顯這些有一部分不是靜態的,比如你使用一個模型User,那么你每次實例化出來他都是一個全新的,互不影響,這里就用到了一個魔術方法__callStatic

舉個栗子:

class Test{

public function __call($name, $arguments)

{

echo 'this is __call'. PHP_EOL;

}

public static function __callStatic($name, $arguments)

{

echo 'this is __callStatic:'. PHP_EOL;

}

}

$test = new Test();

$test->hello();

$test::hi();

//this is __call:hello

//this is __callStatic:hi

當然魔術方法也是很耗性能的一種方式,每次調用的時候后回先掃一遍class沒找到方法時才會調用它,而為了代碼的整潔和抽象這個方法也能給很大的幫助,在這之間去要有個權衡

下面實現的 log 類,采用的就是這種方法,將方法解耦出來,只要符合規定的接口就能調用

class Test{

//獲取 logger 的實體

private static $logger;

public static function getLogger(){

return self::$logger?: self::$logger = self::createLogger();

}

private static function createLogger(){

return new Logger();

}

public static function setLogger(LoggerInterface $logger){

self::$logger = $logger;

}

public function __call($name, $arguments)

{

call_user_func_array([self::getLogger(),$name],$arguments);

}

public static function __callStatic($name, $arguments)

{

forward_static_call_array([self::getLogger(),$name],$arguments);

}

}

interface LoggerInterface{

function info($message,array $content = []);

function alert($messge,array $content = []);

}

class Logger implements LoggerInterface {

function info($message, array $content = [])

{

echo 'this is Log method info' . PHP_EOL;

var_dump($content);

}

function alert($messge, array $content = [])

{

echo 'this is Log method alert: '. $messge . PHP_EOL;

}

}

Test::info('喊個口號:',['好好','學習','天天','向上']);

$test = new Test();

$test->alert('hello');

輸出:

this is Log method info

array(4) {

[0]=>

string(6) "好好"

[1]=>

string(6) "學習"

[2]=>

string(6) "天天"

[3]=>

string(6) "向上"

}

this is Log method alert: hello

也許有的小伙伴已經看出來了,沒錯!這段代碼就是仿照(抄)的 EasyWechat的日志部分,代碼片段

總結

以上是默认站点為你收集整理的php 静态方法 call,php的 __callStatic 函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得默认站点網站內容還不錯,歡迎將默认站点推薦給好友。