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

2019-11-12 18:16:15 +08:00
 JJstyle

贴代码:

    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 精髓😅,后悔没追着问为什么这么做

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

目的就是性能优化。

类似的细节点很多,比如:PHP7 之前还可以用 isset 来判定字符串长短,性能提升明显,PHP7 之后就没必要了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/618906

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX