2011-01-20 93 views
16

可能重複: What is 「:」 in PHP?「:」在PHP中是什麼意思?

什麼是:指的是在下面的PHP代碼?

<?php 
    while (have_posts()) : the_post(); 
?> 
+0

這是一些語言的替代語法構造一樣,如果同時的foreach – 2011-01-20 13:39:15

+3

很難找到,但這裏一些解釋:[參考 - 這是什麼符號意味着PHP? ](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – mario 2011-01-20 13:45:03

+0

哇......謝謝馬里奧:) – 2011-01-20 13:53:03

回答

30

這就是所謂的Alternative Syntax For Control Structures。之後你應該有一個endwhile;。基本上,它允許你從一段時間省略大括號{},使它看起來更「漂亮」...

就你的編輯而言,它被稱爲Ternary Operator(這是第三部分)。基本上這是一個賦值速記。

$foo = $first ? $second : $third; 

是等於說(只是短):

if ($first) { 
    $foo = $second; 
} else { 
    $foo = $third; 
} 
-2
while(expression = true) : run some code ; 
+1

咦?說明很多? – ircmaxell 2011-01-20 13:45:55

+1

明顯的問題=明顯的答案? – 2011-01-20 13:56:42

8

有一個在documentation for while列舉一個例子,解釋了語法:

像與if語句,你可以通過用大括號包圍一組語句或使用替代語法在相同的while循環中對多個語句進行分組:

while (expr): 
    statement 
    ... 
endwhile; 

的回答over here解釋它是這樣的:

這(:)運營商大多是在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> 
5

這個表示法是爲了避免使用花括號 - 通常在將PHP嵌入到HTML中時 - 等同於:

while (have_posts()) 
{ 
    the_post(); 
} 
3

這就是說,而have_posts()true運行the_post()

1
while (expression is true : code is executed if expression is true) 
6

是這樣的:

<?php 
while(have_posts()) { 
    the_post(); 
} 
?>