Drew
Drew

Reputation: 4373

Setting a global variable's value inside an anonymous function

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.

Upvotes: 0

Views: 203

Answers (1)

Sumit Wadhwa
Sumit Wadhwa

Reputation: 3217

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

Upvotes: 1

Related Questions