2012-11-25 111 views
0

我有一個遞歸地打開HTML頁面和提取文章的函數。執行該函數後,返回的數組爲NULL,但是我的跟蹤步驟介於數組實際包含元素之間。我相信在返回數組時它會被重置。爲什麼函數返回後全局數組爲空? (PHP)

爲什麼含在陣列中的功能元件,但是被返回後是NULL?

這是函數(簡體):

function get_content($id,$page=1){ 
    global $content; // store content in a global variable so we can use this function recursively 

    // If $page > 1 : we are in recursion 
    // If $page = 1 : we are just starting 
    if ($page==1) { 
     $content = array(); 
    } 

    $html = $this->open($id,$page)) { 

    $content = array_merge($content, $this->extract_content($html)); 

    $count = count($content); 
    echo("We now have {$count} articles total."); 

    if($this->has_more($html)) { 
     $this->get_content($id,$page+1); 
    } else { 
     $count = count($content); 
     echo("Finished. Found {$count} articles total. Returning results."); 
     return $content; 
    } 
} 

這是我如何調用該函數:

$x = new Extractor(); 
$articles = $x->get_content(1991); 
var_export($articles); 

調用該函數將輸出類似:

We now have 15 articles total. 
We now have 30 articles total. 
We now have 41 articles total. 
Finished. Found 41 articles total. Returning results. 
NULL 

爲什麼數組包含函數中的元素n,但返回後爲NULL?

+0

哪裏收盤'}''爲$ HTML = $這個 - >打開($ ID,$頁)){'? – fuxia

回答

3

return $this->get_content($id,$page+1);嘗試的只是調用函數。

如果您只是在不返回的情況下調用該函數,那麼「初始調用」將不會返回任何內容,並且隨後調用該函數時返回值將丟失。

0

嘗試,如果你還沒有這麼做過第一個函數調用之前聲明$內容。

0

請勿使用全局變量。特別是如果它只是爲了遞歸的緣故。

function get_content($id,$page=1, $content = array()){ 

    $html = $this->open($id,$page)); 

    $content = array_merge($content, $this->extract_content($html)); 

    if($this->has_more($html)) { 
     return $this->get_content($id,$page+1, $content); 
    } else { 
     return $content; 
    } 
} 

請注意,我剝去了所有的調試輸出。

相關問題