Should I prefer one of these snippets over the other and why?
1.
function render()
{
echo "<div>$content&l开发者_如何学Got;/div>";
}
2.
function render()
{
?>
<div><?= $content ?></div>
<?php
}
Both are not a good idea. Cause function is outputting. Try make this way:
function render( $content_, $style_ )
{
$res = "<div{$style_}>$content_</div>";
return $res;
}
...
and then:
echo render( "Content inside div", " style='color:red;'" )
Cause:
- Function is calculating and returning, it's main purpose is this.
- Application is generating, and it can use functions to prepare.
- Your may need to make some header in the future, and good idea is to have start all output at end of script. Using templating like Smarty, so - will save many time for you :)
As a general rule, it's a good idea to keep the contents of each file that makes up your application as uncluttered as possible. Since PHP is a template language and you can have PHP files with wildly different purposes (consider that a file containing pure HTML is a valid PHP file), my personal preference is:
If you need to create a small bit of HTML in code, don't open and close PHP tags.
For example, prefer this:
function render()
{
echo "<div>$content</div>";
}
over this:
function render()
{
?><div><?= $content ?></div><?php
}
Also observe that on the snippet above I have not included any spaces just after the PHP close tag or before the PHP open tag; generally whitespace is not significant in HTML but it can matter in two cases:
- You want to have nicely indented HTML (sometimes helpful while developing)
- The presence of one or more whitespace character vs none at all creates an extra text node in the DOM tree, which might matter
If you want to include this kind of whitespace in the HTML your source code is going to be a bit ugly on the eyes in any case, but definitely uglier if you go with the close/open tag approach.
Isolate large pieces of HTML in views and include small bits of logic as necessary there.
For example, prefer this:
<body>
<div id="blah">
<ul id="nav">
<?php foreach ($navItems as $url => $title) : ?>
<!--
NOTE:
You can opt to make the line below a single echo statement
in PHP rather than HTML with values from PHP substituted
in various places inside, and in this example it might even
be better. However, if the output for each item is more complex
than a li/a pair, it will be far more readable in this form.
-->
<li><a href="<?php echo $url ?>"><?php echo $title ?></a></li>
<?php endforeach; ?>
over this:
$output = '<body><div id="blah"><ul id="nav">';
foreach ($navItems as $url => $title) {
$output .= '<li><a href="'.$url.'">'.$title.'</a></li>
}
echo $output;
精彩评论