V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
JJstyle
V2EX  ›  PHP

Laravel 的 Facade 的这个函数有点没看明白

  •  
  •   JJstyle · 2019-11-12 18:16:15 +08:00 · 4094 次点击
    这是一个创建于 1598 天前的主题,其中的信息可能已经有所发展或是发生改变。

    贴代码:

        public static function __callStatic($method, $args)
        {
            $instance = static::getFacadeRoot();
    
            if (! $instance) {
                throw new RuntimeException('A facade root has not been set.');
            }
    
            switch (count($args)) {
                case 0:
                    return $instance->$method();
                case 1:
                    return $instance->$method($args[0]);
                case 2:
                    return $instance->$method($args[0], $args[1]);
                case 3:
                    return $instance->$method($args[0], $args[1], $args[2]);
                case 4:
                    return $instance->$method($args[0], $args[1], $args[2], $args[3]);
                default:
                    return call_user_func_array([$instance, $method], $args);
            }
        }
    

    直接 return call_user_func_array([$instance, $method], $args); 不好吗?难道判断一下参数数量,速度快一点?

    PS:我记得我以前一个同事也是这么写的,真是深得 Laravel 精髓😅,后悔没追着问为什么这么做

    10 条回复    2019-11-12 21:02:36 +08:00
    Rekkles
        1
    Rekkles  
       2019-11-12 18:27:15 +08:00
    版本多少? 现在是 return $instance->$method(...$args); 一个完事啊
    des
        2
    des  
       2019-11-12 18:31:05 +08:00
    快不快,快多少测一下就知道了啊
    JJstyle
        3
    JJstyle  
    OP
       2019-11-12 18:33:51 +08:00
    agdhole
        4
    agdhole  
       2019-11-12 18:41:52 +08:00
    现在都 6.5 了,5.1 的源码也太老了吧
    mcfog
        5
    mcfog  
       2019-11-12 19:05:56 +08:00 via Android
    就是快
    mcfog
        6
    mcfog  
       2019-11-12 19:12:36 +08:00 via Android   ❤️ 3
    手残发出去了,实际上你可以在很多语言的高度优化的类库里看到类似的东西
    https://github.com/lodash/lodash/blob/4.17.15/lodash.js#L4982
    https://backbonejs.org/docs/backbone.html#section-49
    印象里 jquery 好像也有,懒得找了
    niucility
        7
    niucility  
       2019-11-12 19:21:24 +08:00
    version 5.6
    return $instance->$method(...$args);
    JJstyle
        8
    JJstyle  
    OP
       2019-11-12 20:05:33 +08:00 via iPhone
    @agdhole 项目有点老,没办法升级
    wslsq
        9
    wslsq  
       2019-11-12 20:10:40 +08:00
    mrgeneral
        10
    mrgeneral  
       2019-11-12 21:02:36 +08:00
    善用搜索: https://segmentfault.com/q/1010000012081290

    目的就是性能优化。

    类似的细节点很多,比如:PHP7 之前还可以用 isset 来判定字符串长短,性能提升明显,PHP7 之后就没必要了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1135 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:57 · PVG 06:57 · LAX 15:57 · JFK 18:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.