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


How to use a variable outside the function in PHP?

我的函数:

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?它是数组。"return$urls"不起作用,或者我做错了什么。请帮帮我。

当您将值加载到函数中的$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) {
}

一种更简单的方法是将数据放入一个简单的变量中,并从函数返回

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) {
}