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 函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安全监督备案办理流程(安监备案流程)
- 下一篇: php旧版本windows_Window