In an effort to produce cleaner PHP files, I want to echo less HTML and embed more PHP. I've stumbled upon constructs like the following:
<?php
foreach($allOGroups as $ogroup):
if($lastGroup != $ogroup['group']):
if($lastGroup !== null):
?>
</optgroup>
<?php
endif;
?>
I've googled for a while now but can't seem to find a tutorial on how to use this mysterious 开发者_JAVA技巧":" operator. Can anyone point me in the right direction?
Thanks, MrB
Alternative syntax for control structures:
if ($a == $b) {
echo $a;
}
// is same as:
if ($a == $b):
echo $a;
endif;
This syntax was introduced to make embedding PHP in HTML easier. By telling which block to close the code becomes more understandable.
As you have discovered, the mysterious :
is simply an alternative syntax to opening and closing curly brackets. It's most effective when you're mingling PHP with HTML, since it makes it easier to discover whether you're closing an if
, for
, foreach
or while
structure.
if($foo):
// Do something
endif;
for($i = 0; $i < 10; $i++):
// Do something
endfor;
foreach($foo as $k, $v):
// Do something
endforeach;
while($foo):
// Do something
endwhile;
It's a feature of PHP's conditional constructs. Instead of using braces to punctuate the block, you use :
and the corresponding keyword.
Also, it has nothing to do with embedding PHP or HTML.
: isn't an operator, it's simply part of an alternative syntax for control structures. Personally, I wouldn't use it. There's no benefit over using 'standard' syntax, and I think it's marginally harder to read.
精彩评论