2010-07-16 37 views
3

我看到了下面的代码片段:if和else语句中“:”的用法是什么?

<?php 
if(!empty($_POST)): // case I: what is the usage of the : 
if(isset($_POST['num']) && $_POST['num'] != ''): 

$num = (int)$_POST['num']; 

.... 

if($rows == 0): 
echo 'No'; 

else: // case II: what is usage of : 
echo $rows.'Yes'; 

endif; 

我想知道的是什么用法“:”在PHP代码。

+0

我开了这个问题,认为它是关于某种倒退三元运算 – 2010-07-16 20:12:18

回答

8

这是alternative syntax for control structures替代语法。

所以

if(condition): 
    // code here... 
else: 
    // code here... 
endif; 

相当于

if(condition) { 
    // code here... 
} else { 
    // code here... 
} 

这与HTML打交道时能来非常方便。 Imho,它更易于阅读,因为您不必寻找大括号{},并且PHP代码和HTML不会混淆。例如:

<?php if(somehting): ?> 

    <span>Foo</span> 

<?php else: ?> 

    <span>Bar</span> 

<?php endif; ?> 

我不会使用,虽然“正常” PHP代码的替代语法,因为这里的大括号提供更好的可读性。

+0

的这不是更难读,更容易出错,如果你有一个嵌套如果/别人的? – 2012-12-24 21:52:33

+0

我认为这是主观的。我发现更容易发现一个缺少的<?php结束符;在HTML中比''更简单,因为它占用了更多的空间。 – 2012-12-24 21:54:37

3

这个:运算符主要用于嵌入式编码的php和html。

使用此运算符可以避免使用大括号。该运算符降低了嵌入式编码的复杂性您可以使用,如果使用这个:运营商,而对于,的foreach更多...

没有 ':' 运营商

<body> 
<?php if(true){ ?> 
<span>This is just test</span> 
<?php } ?> 
</body> 

以 ':' 运营商

<body> 
<?php if(true): ?> 
<span>This is just test</span> 
<?php endif; ?> 
</body> 
0

唯一的一次我使用冒号是简写if-else语句

$var = $bool ? 'yes' : 'no'; 

这相当于:

if($bool) 
$var = 'yes'; 
else 
$var = 'no'; 
+1

*简写if-else语句*被称为[**三元运算符**](http://en.wikipedia.org/wiki/Ternary_operation)。 – 2010-07-16 20:21:46

+0

@Felix感谢您的信息! – 2010-07-16 21:17:15