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

laravel 中一段关于闭包的代码

  •  
  •   ma199385 · 2017-11-23 15:10:35 +08:00 · 2935 次点击
    这是一个创建于 2318 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 有什么意义
    
    5 条回复    2017-11-23 23:55:33 +08:00
    Junjunya
        1
    Junjunya  
       2017-11-23 15:27:25 +08:00
    注释已经写的很清楚了呀 就算不懂 ,谷歌或者百度翻译一下也能理解

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

    static 就算设置静态变量的呀
    torbrowserbridge
        2
    torbrowserbridge  
       2017-11-23 15:33:16 +08:00
    防止重复 resolve $container
    ma199385
        3
    ma199385  
    OP
       2017-11-23 15:33:42 +08:00
    我现在理解了,刚才看的不全面,laravel 通过 bind 方法将某些 abstract 和 share 方法返回的闭包通过键值对的形式存储到 bindings 数组中,当再次调用该 abstract 时,不会在闭包中再次声明该对象,我之前想的错了角度
    ma199385
        4
    ma199385  
    OP
       2017-11-23 15:37:47 +08:00
    之前想成不同的 abstract 调用 share 时因为 return function 的原因,所以每次调用闭包时都会生成一次对象,所以此时 static 没有意义,但是忘了 bindings 数组的 abstract 的是会重复利用的
    GreatHumorist
        5
    GreatHumorist  
       2017-11-23 23:55:33 +08:00 via iPhone
    用函数作用域内的静态变量实现的单例模式
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2609 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 573ms · UTC 15:35 · PVG 23:35 · LAX 08:35 · JFK 11:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.