2013-06-20 162 views
0

在閱讀一本關於php的書時,我在一段代碼中找到了一條邏輯上對我沒有意義的代碼。代碼行是一類功能的一部分:php變量分配混淆

private function replaceTags($pp = false) { 
    //get the tags in the page 
    if($pp == false) { 
     $tags = $this->page->getTags(); 
    } else { 
     $tags = $this->page->getPPTags(); 
    } 
    //go through them all 
    foreach($tags as $tag => $data) { 
     //if the tag is an array, then we need to do more than a simple find and replace! 
     if(is_array($data)) { 
      if($data[0] == 'SQL') { 
       //it is a cached query...replace tags from the database 
       $this->replaceDBTags($tag, $data[1]); 
      } elseif($data[0] == 'DATA') { 
       //it is some cahched data...replace tags from cached data 
       $this->replaceTags($tag, $data[1]); 
      } 
     } else { 
      //replace the content 
      $newContent = str_replace('{' . $tag . '}', $data, $this->page->setContent($newContent)); 
      $this->page->setContent($newContent); 
     } 
    } 
} 

這沒有意義,我的具體線路是:

$newContent = str_replace('{' . $tag . '}', $data, $this->page->setContent($newContent)); 

你如何傳遞變量「$ newContent」到「 setContent($ newContent)「何時還沒有值?

任何解釋?

+0

正在生成的內容在哪裏? – Orangepill

回答

0

該語句在for循環中執行,所以$newContent保存在另一個循環中使用的值。

在第一次執行時,$newContent將是空的,但在下一次迭代中它將有一個要替換的值。

foreach($tags as $tag => $data) { 
    if .... 
    } else { 
     //replace the content 
     $newContent = str_replace('{' . $tag . '}', $data, $this->page->setContent($newContent)); 
    //^
    // Now next time when the loop executes again it will have a 
    // $newContent to process. 

     $this->page->setContent($newContent); 
    } 
} 
+0

你會發現這是我感到困惑的地方,因爲實際上setContent方法不過是一個setter,並且不會返回任何東西。 –

+0

@robertrocha,'$ this - > page - > setContent()'可能會返回一些東西。即使是空字符串。做'var_dump($ this - > page - > setContent($ newContent));'看看它返回的結果。 – Starx

0

你爲什麼認爲這個變量「$ newContent」沒有值?其實,它被設置在上面的行。

無論如何,您可以將一個空變量傳遞給函數。與

+0

我在說的是上面那行正在分配的行號 –

0

最後一個參數沒有問題是一個回調函數,所以其分配

+1

怎麼會這樣?我不這麼認爲。 –

+0

回撥?功能? – Starx

0

如果一個變量沒有被分配,因爲如果它包含null它的處理後調用。如果啓用了警告,則會導致記錄「未定義變量」警告,但腳本仍將運行。最有可能的,setContent()函數檢查它的參數是否爲null,如果是這樣,它只是返回當前內容而不修改它。

但是這段代碼對我來說似乎非常可疑。它每次通過循環呼叫setContent()兩次。第一行應該只需要使用getContent(),這不需要參數。