PHP鲜为人知的可选语法形式
你知道PHP有一种可选的语法结构吗?直到我开始写wordpress主题时,我才了解。当时看到那种奇怪的写法,我去php.net查询了一下,找到了这篇文章。(http://php.net/manual/en/control-structures.alternative-syntax.php) PHP的这种可选语法可以让PHP更加的简单和易读。控制结构if,while,for,foreach,及switch都有相应的可选语法。通常来说,我推荐在将PHP和HTML混编的时候使用这种可选的语法。
下面看几个具体的例子。
If Example
ForEach Example
While Example
下面看几个具体的例子。
If Example
// This....
if($myString == "foo"):
echo "bar";
else:
echo "no-foo-bar";
endif;
//...is equal to this.
if($myString == "food") {
echo "bar";
} else {
echo "no-foo-bar";
}
ForEach Example
$names = array("bob", "tom", "john");
//This....
foreach($names as $name):
echo "Your name is: {$name}";
endforeach;
//...is equal to this.
foreach($names as $name) {
echo "Your name is: {$name}";
}
While Example
$finaldir = \'download\';
$finished = false; // we\'re not finished yet (we just started)
while ( ! $finished ): // while not finished
$rn = rand(); // random number
$outfile = $finaldir.\'/\'.$rn.\'.gif\'; // output file name
if ( ! file_exists($outfile) ): // if file DOES NOT exist...
$finished = true; // ...we are finished
endif;
endwhile; // (if not finished, re-start WHILE loop)