2013-06-20 164 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(),这不需要参数。