php showstatic函数,php的 __callStatic 函数

本文探讨了PHP中魔术方法__call和__callStatic的使用,特别是在Laravel框架中的常见实践。通过示例展示了如何通过这两个方法实现动态调用非静态方法,以及在性能和代码抽象之间的权衡。文中还仿照EasyWechat的日志部分,创建了一个名为Test的类,用于解耦和调用日志方法。通过这两个魔术方法,可以将方法调用委托给特定的logger实例,确保代码的整洁和灵活性。
摘要由CSDN通过智能技术生成

现在很多框架中调用方法都是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的日志部分,代码片段

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值