2010-07-16 36 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