0

I am using Goutte to crawl a site. I am trying to set the $node->text() value to a global variable, $myGlobalVar, inside the ->each(function ($node) {..}); anonymous function.

$myGlobalVar = '';

$crawler->filter('.the-link-class')->each(function ($node) {
    if($myGlobalVar == ''){
        print "using first " . $node->text() . "\n";
        $myGlobalVar = $node->text();            
    }
});

print "myGlobalVar: " . $myGlobalVar . "\n"; # always empty !!!!!!

I have also tried the use(&$myGlobalVar) closure syntax that was suggested in this answer I found. When I modify the relevant code to ->each(function use(&$myGlobalVar) ($node) {.. I get a syntax error.

Drew
  • 4,215
  • 3
  • 26
  • 40

1 Answers1

1

Your syntax is invalid.

Please change from:

->each(function use(&$myGlobalVar) ($node) {..

to:

->each(function ($node) use(&$myGlobalVar) {..

Also, If the variable $myGlobalVar is declared in the global scope, then you can use the global keyword to directly access and modify the variable

Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34