在匿名函数中设置全局变量的值



我正在使用Goutte对网站进行爬网。我正在尝试将$node->text()值设置为->each(function ($node) {..});匿名函数中的全局变量$myGlobalVar

$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 !!!!!!

我还尝试了use(&$myGlobalVar)闭包语法,它在我找到的这个答案中提出。当我将相关代码修改为->each(function use(&$myGlobalVar) ($node) {..时,我会出现语法错误。

您的语法无效。

请更改自:

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

至:

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

此外,如果变量$myGlobalVar是在全局范围内声明的,那么您可以使用全局关键字直接访问和修改变量

最新更新