如何在PHP中使用函数外的变量?

时间:2016-04-16 17:34:50

标签: php function return

我的功能:

function raspislinks($url)
{
    $chs = curl_init($url);
    curl_setopt($chs, CURLOPT_URL, $url);
    curl_setopt($chs, CURLOPT_COOKIEFILE, 'cookies.txt'); //Подставляем куки раз 
    curl_setopt($chs, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($chs, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36 OPR/29.0.1795.60");
    curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, 0); // не проверять SSL сертификат
    curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, 0); // не проверять Host SSL сертификата
    curl_setopt($chs, CURLOPT_COOKIEJAR, 'cookies.txt'); //Подставляем куки два
    $htmll = curl_exec($chs);
    $pos   = strpos($htmll, '<strong><em><font color="green"> <h1>');
    $htmll = substr($htmll, $pos);
    $pos   = strpos($htmll, '<!--                </main>-->');
    $htmll = substr($htmll, 0, $pos);
    $htmll = end(explode('<strong><em><font color="green"> <h1>', $htmll));
    $htmll = str_replace('<a href ="', '<a href ="https://nfbgu.ru/timetable/fulltime/', $htmll);
    $GLOBALS['urls'];
    preg_match_all("/<[Aa][ \r\n\t]{1}[^>]*[Hh][Rr][Ee][Ff][^=]*=[ '\"\n\r\t]*([^ \"'>\r\n\t#]+)[^>]*>/", $htmll, $urls);
    curl_close($chs);
}

如何在函数外部使用变量$ urls?这是阵列。 “返回$ urls”无法正常工作或我做错了什么。请帮帮我。

1 个答案:

答案 0 :(得分:1)

当您在函数中将值加载到$GLOBALS['urls'];时,您可以在此函数外的代码中使用$urls

$GLOBALS数组为全局范围中可用的每个变量保留一个,因此设置$GLOBALS['urls'];后,该值也可以引用为$urls

喜欢

function raspislinks($url) {

 ...

    //$GLOBALS['urls'];
    preg_match_all("/<[Aa][ \r\n\t]{1}[^>]*[Hh][Rr][Ee][Ff][^=]*=[ '\"\n\r\t]*([^ \"'>\r\n\t#]+)[^>]*>/",
                      $htmll, 
                      $GLOBALS['urls']
                   );

}

raspislinks('google.com');
foreach ( $urls as $url) {

}

更简单的方法是将数据放在一个简单的varibale中并从函数

返回
function raspislinks($url) {

 ...

    //$GLOBALS['urls'];
    preg_match_all("/<[Aa][ \r\n\t]{1}[^>]*[Hh][Rr][Ee][Ff][^=]*=[ '\"\n\r\t]*([^ \"'>\r\n\t#]+)[^>]*>/",
                      $htmll, 
                      $t
                   );
    return $t;
}

$urls = raspislinks('google.com');
foreach ( $urls as $url) {

}