Heredocs are also an option, but they screw up the formatting of the code (since you can't have whitespace before the end token), as well as being very slow. An output buffer would actually be more efficient.
bluewalrus: instead of:
Code:
<?php
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>';
echo get_title_text();
echo '</title></head><body><p>'
echo get_body_text();
echo '</p></body></html>';
?>
... or something silly like that, write:
Code:
<?php
$title = get_title_text();
$body = get_body_text();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php echo $title; ?>
</title>
</head>
<body>
<p>
<?php echo $body; ?>
</p>
</body>
</html>
It has four added benefits:- readability, since you can format the code nicely for output rather than worrying about what the containing PHP looks like;
- efficiency, since the whole thing doesn't have to be parsed as PHP;
- simplicity, as it doesn't require you to follow escaping rules for strings; and
- clear distinction between code and output, which provides three benefits of its own:
- allows you to store the output template in a different place (e.g. in a different file);
- allows you to completely change what's to be output at any point in the code; and
- allows you to start a session without worrying about whether the flow of code has caused output to happen at some point previously.
See also Smarty, which provides a mechanism and assorted tools for further separation of code and content.
Bookmarks