While reading a book about php I cam across a piece of code that logically doesn't make sense to me. The line of code is part of a class function:
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 );
}
}
}
The specific line that doesn't make sense to me is:
$newContent = str_replace( '{' . $tag . '}', $data, $this->page->setContent( $newContent ) );
How can you pass the variable "$newContent" to "setContent( $newContent )" when it doesn't have a value yet?
Any explanations?
That statement is executing in a for loop so, $newContent
will hold the value in another loop to use.
In the first execution, $newContent
will be empty but on the next iteration it will have a value to replace.
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 );
}
}
Why do you think this variable "$newContent" doesn't have a value? Actually, it was set on the line above.
And anyway, you can pass an empty variable to a function. No problem with that
The last parameter is a callback function, so its called after the assignment
If a variable hasn't been assigned, it's treated as if it contains null
. If you have warnings enabled, this will cause an "Undefined variable" warning to be logged, but the script will still run. Most likely, the setContent()
function checks whether its argument is null
, and if so it just returns the current contents without modifying it.
But this code seems very suspect to me. It's calling setContent()
twice each time through the loop. The first line should only need to use getContent()
, which shouldn't need an argument.