0

Why is this code returning null?

public function getPrice($crawler){
        $price = '';

            $crawler->filter('#j-sku-price')->each(
            function ($node) {
            $price = $node->text();
            });

return $price;

If I write it like this

public function getPrice($crawler){
        $price = '';

            $crawler->filter('#j-sku-price')->each(
            function ($node) {
            $price = $node->text();
                print($price);
            });

It works. But I want to return $price at the end.

  • its the scope of your function, to allow the initialized value `$price` to be written (parent scope), use the `use` keyword and import it into the closure. `function ($node) use (&$price)` like so – Kevin May 17 '19 at 02:00

1 Answers1

0

You will get the price in $price_array

$price_array = '';
public function getPrice($crawler {
    $crawler->filter('#j-sku-price')->each(function($node) {
        $price = $node->text();
        array_push($price_array,$price);
    });
    return $price_array;
}
Kirsten Phukon
  • 314
  • 3
  • 17