Your code index.php is correct. I include the updated code for common.php below, then I will explain the differences.
<?php $class = ($page == 'one') ? 'class="active"' : ''; $nav = <<<EOD <div id="nav"> <ul> <li><a $class href="index.php">Tab1</a>/</li> <li><a href="two.php">Tab2</a></li> <li><a href="three.php">Tab3</a></li> </ul> </div> EOD; ?>
The first problem is that you need to make sure that the final declaration for your heredoc is EOD; - has no indentation at all. If he retreated, you will get errors.
As for your problem with PHP code that does not work in the heredoc statement, this is because you are looking at it wrong. Using the heredoc statement does not match closing PHP tags. Thus, you do not need to try to re-open them. It will do nothing for you. The way the heredoc syntax works is that everything between opening and closing is displayed exactly as it is written, with the exception of variables. They are replaced by the corresponding value. I removed your logic from heredoc and used a tertiary function to define the class to make it easier to see (although I do not believe that any logical statements will work in heredoc anyway)
To understand the heredoc syntax, it is the same as enclosing in double quotes ("), but without the need for escaping. Thus, your code can also be written as follows:
<?php $class = ($page == 'one') ? 'class="active"' : ''; $nav = "<div id=\"nav\"> <ul> <li><a $class href=\"index.php\">Tab1</a>/</li> <li><a href=\"two.php\">Tab2</a></li> <li><a href=\"three.php\">Tab3</a></li> </ul> </div>"; ?>
He will do the same, just written a little differently. Another difference between the heredoc and the string is that you can exit the string in the middle where you cannot in the heredoc. Using this logic, you can create the following code:
<?php $nav = "<div id=\"nav\"> <ul> <li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li> <li><a href=\"two.php\">Tab2</a></li> <li><a href=\"three.php\">Tab3</a></li> </ul> </div>"; ?>
You can then include the logic directly in the string, as you originally intended.
Whatever method you choose, there is very little (if any) difference in script performance. It mainly depends on preferences. In any case, you need to make sure that you understand how they work.
Joseph May 26 '10 at 14:08 2010-05-26 14:08
source share