laravel 中一段关于闭包的代码

2017-11-23 15:10:35 +08:00
 ma199385
public function share(Closure $closure)
    {
        return function ($container) use ($closure) {
            // We'll simply declare a static variable within the Closures and if it has
            // not been set we will execute the given Closures to resolve this value
            // and return it back to these consumers of the method as an instance.
            static $object;

            if (is_null($object)) {
                $object = $closure($container);
            }

            return $object;
        };
    }
这段代码中 static 有什么意义
2969 次点击
所在节点    PHP
5 条回复
Junjunya
2017-11-23 15:27:25 +08:00
注释已经写的很清楚了呀 就算不懂 ,谷歌或者百度翻译一下也能理解

```
#我们只需在闭包中声明一个静态变量,如果它有
#没有设置,我们将执行给定的闭包来解析这个值。
#并将其返回给方法的这些消费者作为实例。
```

static 就算设置静态变量的呀
torbrowserbridge
2017-11-23 15:33:16 +08:00
防止重复 resolve $container
ma199385
2017-11-23 15:33:42 +08:00
我现在理解了,刚才看的不全面,laravel 通过 bind 方法将某些 abstract 和 share 方法返回的闭包通过键值对的形式存储到 bindings 数组中,当再次调用该 abstract 时,不会在闭包中再次声明该对象,我之前想的错了角度
ma199385
2017-11-23 15:37:47 +08:00
之前想成不同的 abstract 调用 share 时因为 return function 的原因,所以每次调用闭包时都会生成一次对象,所以此时 static 没有意义,但是忘了 bindings 数组的 abstract 的是会重复利用的
GreatHumorist
2017-11-23 23:55:33 +08:00
用函数作用域内的静态变量实现的单例模式

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

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

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

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

© 2021 V2EX