2014-09-28 23 views
0

我试图让变量$匹配在此函数之外使用。所以我可以使用echo $ matches [0] [0];或$匹配[0] [1];该函数在我的文档中使用后。到目前为止,我还没有能够在函数外部使用matches变量。

function curlLink($url, $regex) 
{ 
     include ('lib/dBug.php'); 
     require_once('lib/curl_http_client.php'); 
     $curl = &new Curl_HTTP_Client(); 
     //$useragent = "Googlebot/2.1 (+http://www.google.com/bot.html)"; 
     $useragent = "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0"; 
     $curl->set_user_agent($useragent); 
     ini_set('max_execution_time','0'); 
     $x=0; 
     $matches = array(); 
     while (sizeof($matches) == 0 && $x < 15) { 
      $html_data = $curl->fetch_url($url); 
      preg_match_all($regex, $html_data, $matches); 
      $x++; 
      array_shift($matches); 
     } 
     if (empty($matches[0][0])) { 
      echo '<img src=\"/img/bigbrokenlink.png\" /><br /><br /> 
      <b>Sorry, no results from your search!</b><br />'; 
     } 
     if (!empty($matches[0][0])) { 
      //return $matches; //This doesn't seem to return a usable variable... 
      $dBug = new dBug ($matches); 
     } 
} 
+0

从函数返回并使用它? – tfrascaroli 2014-09-28 20:38:05

+0

define“似乎没有返回一个可用的变量” – raina77ow 2014-09-28 20:38:56

+0

你是什么意思“这似乎没有返回一个可用的变量......” – Steve 2014-09-28 20:39:07

回答

1

声明 $matches = array();之外的功能随着全球variable.or return it to some function和使用。

如:

global $matches; 
function curlLink($url, $regex) 
{ 
    global $matches; 
// implementation 
} 

//这里访问$matches;

1

设置通过下面的例子将变量作为global

global $matches; 
function curlLink($url, $regex) 
{ 
    global $matches; 

或通话后恢复它,看来你是现在没有返回任何东西。

 if (!empty($matches[0][0])) { 
      //return $matches; //This doesn't seem to return a usable variable... 
      $dBug = new dBug ($matches); 
     } 
     return $matches; 
} 
$returned_matches = curlLink($url, $regex); 
0

您可以使它成为全球,但可能不需要。你应该做的是:

  • 变化的第一行function curlLink ($url, $regex, &$matchesOut)

  • 在函数结束时,使用$matchesOut = $matches

  • 您现在可以使用:

$matches = array(); curlLink(arg1, arg2, $matches); echo $matches[0];

+0

我想尝试这种解决方案,但我似乎无法让这个工作。我也找不到在函数中使用&$ var的文档。 – 2014-09-28 21:25:56

+0

即使你不能使用它,也不要使用全局变量。 http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why – 2014-09-28 21:27:36

+0

这里是文档; http://php.net/manual/en/functions.arguments.php#functions.arguments.by-reference – 2014-09-28 21:28:12