简体   繁体   中英

Anonymous functions in PHP

I'm developing a web scraper for the Android Play Store in PHP, and i have some trouble. This is the function i use to get app comments:

function reviews($url_to_crawl , $crawler)  {
        $reviews_contents = array();
        if (num_reviews($url_to_crawl, $crawler)) {
                $crawler->filter('.review-body')->each(function(Symfony\Component\DomCrawler\Crawler $node, $i) use ($reviews_contents) {
            $reviews_contents[$i] = trim($node->text());
            });
        }
        return $reviews_contents;
 }

now $reviews_contents is empty, i guess because i use an anonymous function. Is there another way to do this?

您需要在这样的use通过引用传递变量$reviews_contents

function(Symfony\Component\DomCrawler\Crawler $node, $i) use (&$reviews_contents)

Because use in anonymous functions passes variables by value instead of by reference. You want a reference so you can modify the variable and have those modifications stick around after the function gets called.

function (Symfony\Component\DomCrawler\Crawler $node, $i) use (&$reviews_contents) {
   // modifications to `$reviews_contents` will stick around because it's now
   // a reference, not passed by value
}

尝试将&放在$ reviews_contents之前,如下所示,以获取对该变量的引用...

use (&$reviews_contents) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM