2012-11-25 2 views
0

나는 HTML 페이지를 반복적으로 열고 기사를 추출하는 함수를 가지고있다. 함수를 실행 한 후에 반환 된 배열은 NULL이지만 그 사이의 추적 단계는 배열에 실제로 요소가 있음을 나타냅니다. 배열을 반환 할 때 재설정 될 것이라고 생각합니다.함수가 반환 한 후에 전역 배열이 비어있는 이유는 무엇입니까? (PHP)

왜 배열에 함수가 있지만 반환 된 후에 NULL입니까?

$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 

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; 
    } 
} 

이 내가 함수를 호출하는 방법입니다

함수 (간체)입니다 배열에 요소가 포함 된 이유는 무엇입니까? n하지만 반환 된 후 NULL입니까?

+0

'$ html = $ this-> open ($ id, $ page)) {'? – fuxia

답변

3

그냥 함수를 호출하는 대신 return $this->get_content($id,$page+1);을 사용해보십시오.

반환하지 않고 함수를 호출하면 "초기 호출"은 아무 것도 반환하지 않으며 함수의 후속 호출에 대해 반환 값이 손실됩니다.

0

아직 수행하지 않은 경우 첫 번째 함수 호출 전에 $ content를 선언하십시오.

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; 
    } 
} 

모든 디버깅 출력을 제거했습니다.

관련 문제