使用匿名函数中的变量

时间:2016-10-08 13:36:37

标签: php return anonymous-function

鉴于以下功能,我需要calculateProducts()来返回$products数组。

public function calculateProducts($params)  {

     SoapWrapper::service('calculateProducts', 
        function ($service) use ($data) {
          $listProducts = $service->call('calculateProducts');
          foreach ($listProducts->return->productList as $pdt) {
              $product = new ProductsResult;
              $product->valueA = "a";
              $product->valueB  = "b";
              $product->save();
              $products[] = $product;
          }
        }
    );
    return $products;
}

这不起作用:我想我正在弄乱匿名函数(我现在很难读好这些函数),因为$products已进入它。

如何使$products“全局”以便calculateProducts()可以返回它?

我试图将$products返回到匿名函数然后返回SoapWrapper对象的值,当然这不会返回所需的ProductsResult对象数组,如下所示:

 public function calculateProducts($params)  {

         $pdts = SoapWrapper::service('calculateProducts', 
            function ($service) use ($data) {
              $listProducts = $service->call('calculateProducts');
              foreach ($listProducts->return->productList as $pdt) {
                  $product = new ProductsResult;
                  $product->valueA = "a";
                  $product->valueB  = "b";
                  $product->save();
                  $products[] = $product;
              }
            return $products;
           }
        );
        return $pdts;
    }

1 个答案:

答案 0 :(得分:0)

我找到了答案。

应该使用闭包:

public function calculateProducts($params)  {
     function ($service) use ($data, &$products) {
          $listProducts = $service->call('calculateProducts');
          foreach ($listProducts->return->productList as $pdt) {
              $product = new ProductsResult;
              $product->valueA = "a";
              $product->valueB  = "b";
              $product->save();
              $products[] = $product;
          }
        }
    return $products;
}

这里的线索是function ($service) use ($data, &$products) {}