如何在 foreach 循环内访问 PHP 中的变量?

How do I access a variable in PHP inside a foreach loop?

我正在 webscraping 来自 this link using the Goute Library 的 table php。

下面是我的代码

    $client = new Client();
    $crawler = $client->request('GET', 'https://www.worldometers.info/world-population/population-by-country/');
    $crawler->filter('#example2 tbody')->filter('tr')->each(function ($node) {

       $country = new Country(); // I have declared country here.
       $test = "TOday";   //I have a variable Test

        $node->filter('td')->each(function ($td,$i){

            switch ($i){
                case 1:
                    $country_name = $td->text();

                    echo $test; //I cannot access test here.
                    $country->name = $country_name; //I am not able to access the declared Country here

                    break;
                case 2:
                    //todo case 2
                    break;
                case 3:
                    //todo case 3
                    break;
                case 4:
                    //todo case 4
                    break;
            }
        });

        echo "<br><br><br>";

    });

我的代码包含两个 foreach 循环。在第一个循环中,我声明了我想在第二个循环中访问的变量 $test 和 $country。

但是,每当我尝试访问变量时,都会收到错误消息:

"Undefined variable: test"

以下是 PhpStorm 的屏幕截图。

为什么我无法访问这些已经明确声明甚至初始化的变量?

如果你想在你的函数 clouser 中访问这个变量,你应该告诉那个函数使用它们:

 $crawler->filter('#example2 tbody')->filter('tr')->each(function ($node)use( $country) {

   $country = new Country(); // I have declared country here.
   $test = "TOday";   //I have a variable Test

如果您想使用其他变量,只需将其添加到函数参数即可:

->each(function ($node)use( $country,$secondVariable,$thirdVariable ...)