Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在foreach循环中访问PHP中的变量?_Php_Laravel_Goutte - Fatal编程技术网

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

如何在foreach循环中访问PHP中的变量?,php,laravel,goutte,Php,Laravel,Goutte,我正在使用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) {

我正在使用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>";

    });
$client=newclient();
$crawler=$client->request('GET','https://www.worldometers.info/world-population/population-by-country/');
$crawler->filter('#example2 tbody')->filter('tr')->每个函数($node){
$country=newcountry();//我已经在这里声明了国家。
$test=“TOday”//我有一个变量测试
$node->filter('td')->每个(函数($td,$i){
交换机(一美元){
案例1:
$country_name=$td->text();
echo$test;//我无法在此处访问测试。
$country->name=$country\u name;//我无法访问此处声明的国家/地区
打破
案例2:
//待办事项案例2
打破
案例3:
//待办事项个案3
打破
案例4:
//待办事项案例4
打破
}
});
回声“


”; });
我的代码包含两个foreach循环。在第一个循环中,我声明变量$test和$country,我希望在第二个循环中访问它们

但是,每当我尝试访问变量时,都会出现以下错误:

“未定义变量:测试”

下面是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
如果要使用另一个vaiable,只需将其添加到函数参数:

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