首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >laravel闭包函数外部的访问变量

laravel闭包函数外部的访问变量
EN

Stack Overflow用户
提问于 2021-02-26 22:24:17
回答 1查看 345关注 0票数 0

我使用的是Laravel 8和PHP 8。

我在全局作用域中定义了一个变量,并为其分配了null值。

我使用了laravel集合的each函数来迭代每个元素。在这个闭包中,我还有另一个闭包,那就是集合的filter函数。我将filter function的输出赋值给全局变量,它正在工作,但仅在each函数的闭包内。(使用xdebug检查)

在闭包外部,变量再次变为null,即使我在闭包内部使用use()函数传递了变量,但它仍然不起作用。

代码语言:javascript
复制
$filtered = null;

$product->each(function ($price) use($coupons, $filtered) {

    $filtered = $coupons->filter(function ($coupon) use($price) {
        if (!empty($price->iso_code)) {
            if ($coupon->iso_code = $price->iso_code) {
                $a = $price->currency_code;
                $b = $coupon->currency_code;
                return $a == $b;
            }
        }
        return $price->currency_code = $coupon->currency_code;
    });

});

return $filtered; //null

我已经推荐了this answer & this also,但没有运气。

有人可以指导我如何将filter函数的输出赋给全局变量吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-26 22:29:04

要在闭包之外获得更改效果,您需要使用引用,如下所示

PHP Docs

代码语言:javascript
复制
$filtered = null;

$product->each(function ($price) use($coupons, &$filtered) {

    $filtered = $coupons->filter(function ($coupon) use($price) {
        if (!empty($price->iso_code)) {
            if ($coupon->iso_code = $price->iso_code) {
                $a = $price->currency_code;
                $b = $coupon->currency_code;
                return $a == $b;
            }
        }
        return $price->currency_code = $coupon->currency_code;
    });

});

return $filtered;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66387557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档