如何在函数外键入值

时间:2019-04-06 08:32:14

标签: php function symfony

我想要功能之外的$ name值,以便我可以用它重命名zip文件,但是该怎么做?

这种Crawele方法,我不能使用函数外部的值

<?php

require 'vendor/autoload.php';

use Symfony\Component\DomCrawler\Crawler;

$client = new \GuzzleHttp\Client();
// go get the date from url
$url = 'https://hentaifox.com/gallery/58118/';

$resnm = $client->request('GET', $url);

$htmlnm = ''.$resnm->getBody();

$crawler = new Crawler($html);

$res_name = $client->request('GET', $url);

$html_name = ''.$res_name->getBody();

$crawler_name = new Crawler($html_name);

$nameValues_name = $crawler_name->filter('.info > h1')->reduce(function (Crawler $node, $i){
    $name = $node->text();
    return $maname;
});

print_r($name);
$res = $client->request('GET', $url);

$html = ''.$res->getBody();

$crawler = new Crawler($html);

$nodeValues = $crawler->filter('.gallery .preview_thumb')->each(function (Crawler $node, $i) {
     $image = $node->filter('img')->attr('data-src');
     $imagerep = str_replace(array('//i2.hentaifox.com' , '//i.hentaifox.com','t.jpg'),array('https://i2.hentaifox.com','https://i2.hentaifox.com','.jpg'),$image);
     $zip = new ZipArchive();

     $my_save_dir = $name.'.zip';

     $zip->open($my_save_dir, ZipArchive::CREATE);

     $imgdownload = file_get_contents($imagerep);

     $zip->addFromString(basename($imagerep), $imgdownload);

     $zip->close();

});

帮我找出$ name的值,以便用它来命名$ my_save_dir中的zip文件

2 个答案:

答案 0 :(得分:1)

如果要从外部使用变量,请在anonymous function内部使用此变量:

$nodeValues = $crawler->filter('.gallery .preview_thumb')
                      ->each(function (Crawler $node, $i) use ($name) {

如果您还希望能够访问匿名函数内部对变量所做的任何更改,则需要pass it by reference

$nodeValues = $crawler->filter('.gallery .preview_thumb')
                      ->each(function (Crawler $node, $i) use (&$name) {

您也可以将$name声明为global变量,但这通常被认为是不好的做法,您始终需要对其进行跟踪。

答案 1 :(得分:0)

匿名函数可以使用use子句从其周围的范围继承数据(请参见https://www.php.net/manual/en/functions.anonymous.php上的示例3)

// $name has to be defined here.
$nodeValues = $crawler->filter('.gallery .preview_thumb')
                      ->each(function (Crawler $node, $i) use ($name) { // <-- the use
     //...
});

但是,我有一种奇怪的感觉,因为当您一直不使用map-reduce原理时,如果不一直使用匿名函数,您的状况会更好。我想这也将更容易也很好:

foreach($crawler->filter('.gallery .preview_thumb') as $i => $node) {
    // it's the same scope now
    // do whatever ...
}

但是,为什么不在循环的 外部打开Zip文件,而只在循环中添加内容呢?!