PHP中的__callStatic函数如何使用

 4524

这种情况在larave中尤其常见,但是开发过程中很明显这些有一部分不是静态的,比如你使用一个模型User,那么你每次实例化出来他都是一个全新的,互不影响,这里就用到了一个魔术方法__callStatic


PHP中的__callStatic函数如何使用


举个栗子:

  1. <?php
  2. class Test{
  3.     public function __call($name, $arguments)
  4.     {
  5.         echo 'this is __call'. PHP_EOL;
  6.     }
  7.  
  8.     public static function __callStatic($name, $arguments)
  9.     {
  10.         echo 'this is __callStatic:'. PHP_EOL;
  11.     }
  12. }
  13.  
  14. $test = new Test();
  15. $test->hello();
  16. $test::hi();
  17. //this is __call:hello
  18. //this is __callStatic:hi

当然魔术方法也是很耗性能的一种方式,每次调用的时候后回先扫一遍class没找到方法时才会调用它,而为了代码的整洁和抽象这个方法也能给很大的帮助,在这之间去要有个权衡

下面实现的 log 类,采用的就是这种方法,将方法解耦出来,只要符合规定的接口就能调用

  1. <?php
  2.  
  3. class Test{
  4.     //获取 logger 的实体
  5.     private static $logger;
  6.  
  7.     public static function getLogger(){
  8.         return self::$logger?: self::$logger = self::createLogger();
  9.     }
  10.  
  11.     private static function createLogger(){
  12.         return new Logger();
  13.     }
  14.  
  15.     public static function setLogger(LoggerInterface $logger){
  16.         self::$logger = $logger;
  17.     }
  18.  
  19.  
  20.     public function __call($name, $arguments)
  21.     {
  22.         call_user_func_array([self::getLogger(),$name],$arguments);
  23.     }
  24.  
  25.     public static function __callStatic($name, $arguments)
  26.     {
  27.         forward_static_call_array([self::getLogger(),$name],$arguments);
  28.     }
  29. }
  30.  
  31. interface LoggerInterface{
  32.     function info($message,array $content = []);
  33.     function alert($messge,array $content = []);
  34. }
  35.  
  36. class Logger implements LoggerInterface {
  37.     function info($message, array $content = [])
  38.     {
  39.         echo 'this is Log method info' . PHP_EOL;
  40.         var_dump($content);
  41.     }
  42.  
  43.     function alert($messge, array $content = [])
  44.     {
  45.         echo 'this is Log method alert: '. $messge . PHP_EOL;
  46.     }
  47. }
  48.  
  49.  
  50. Test::info('喊个口号:',['好好','学习','天天','向上']);
  51. $test = new Test();
  52. $test->alert('hello');

输出:

  1. this is Log method info
  2. array(4) {
  3.   [0]=>
  4.   string(6) "好好"
  5.   [1]=>
  6.   string(6) "学习"
  7.   [2]=>
  8.   string(6) "天天"
  9.   [3]=>
  10.   string(6) "向上"
  11. }
  12. this is Log method alert: hello


TAG标签:
本文网址:https://www.zztuku.com/detail-9005.html
站长图库 - PHP中的__callStatic函数如何使用
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐