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 Closurs 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 有什么意义
1 Junjunya 2017-11-23 15:27:25 +08:00 注释已经写的很清楚了呀 就算不懂 ,谷歌或者百度翻译一下也能理解 ``` #我们只需在闭包中声明一个静态变量,如果它有 #没有设置,我们将执行给定的闭包来解析这个值。 #并将其返回给方法的这些消费者作为实例。 ``` static 就算设置静态变量的呀 |
![]() | 2 torbrowserbridge 2017-11-23 15:33:16 +08:00 防止重复 resolve $container |
3 ma199385 OP 我现在理解了,刚才看的不全面,laravel 通过 bind 方法将某些 abstract 和 share 方法返回的闭包通过键值对的形式存储到 bindings 数组中,当再次调用该 abstract 时,不会在闭包中再次声明该对象,我之前想的错了角度 |
4 ma199385 OP 之前想成不同的 abstract 调用 share 时因为 return function 的原因,所以每次调用闭包时都会生成一次对象,所以此时 static 没有意义,但是忘了 bindings 数组的 abstract 的是会重复利用的 |
![]() | 5 GreatHumorist 2017-11-23 23:55:33 +08:00 via iPhone 用函数作用域内的静态变量实现的单例模式 |