通常,你希望根據(jù)條件執(zhí)行多于一條語句。當(dāng)然,不需要給每條語句都加上 if 判斷。取而代之,可以把多條語句組成一個語句組。 if語句可以嵌套于其他 if語句中,使你能夠靈活地有條件的執(zhí)行程序的各個部分。
2、 else語句
通常你希望滿足特定條件時執(zhí)行一條語句,不滿足條件是執(zhí)行另一條語句。else就是用來做這個的。else 擴(kuò)展if語句,在if語句表達(dá)式為false時執(zhí)行另一條語句。例如, 下面程序執(zhí)行如果 $a 大于 $b則顯示 /'a is bigger than b/',否則顯示 /'a is not bigger than b/':
if ($a>$b) { print /"a is bigger than b/"; } else { print /"a is not bigger than b/"; }
3、 elseif語句
elseif,就象名字所示,是if和else的組合,類似于 else,它擴(kuò)展 if 語句在if表達(dá)式為 false時執(zhí)行其他的語句。但與else不同,它只在elseif表達(dá)式也為true時執(zhí)行其他語句。
function foo( &$bar ) { $bar .= /' and something extra./'; } $str = /'this is a string, /'; foo( $str ); echo $str; // outputs /'this is a string, and something extra./'
function foo( $bar ) { $bar .= /' and something extra./'; } $str = /'this is a string, /'; foo( $str ); echo $str; // outputs /'this is a string, /' foo( &$str ); echo $str; // outputs /'this is a string, and something extra./'
4、 默認(rèn)值
函數(shù)可以定義 c++ 風(fēng)格的默認(rèn)值,如下:
function makecoffee( $type = /"cappucino/" ) { echo /"making a cup of $type.//n/"; } echo makecoffee(); echo makecoffee( /"espresso/" );
上邊這段代碼的輸出是:
making a cup of cappucino. making a cup of espresso. 注意,當(dāng)使用默認(rèn)參數(shù)時,所有有默認(rèn)值的參數(shù)應(yīng)在無默認(rèn)值的參數(shù)的后邊定義;否則,將不會按所想的那樣工作。
5、class(類)
類是一系列變量和函數(shù)的集合。類用以下語法定義:
<?php class cart { var $items; // items in our shopping cart // add $num articles of $artnr to the cart function add_item($artnr, $num) { $this->items[$artnr] += $num; } // take $num articles of $artnr out of the cart function remove_item($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } else { return false; } } } ?>
$ncart = new named_cart; // create a named cart $ncart->set_owner(/"kris/"); // name that cart print $ncart->owner; // print the cart owners name $ncart->add_item(/"10/", 1); // (inherited functionality from cart)
class constructor_cart { function constructor_cart($item = /"10/", $num = 1) { $this->add_item($item, $num); } } // shop the same old boring stuff. $default_cart = new constructor_cart; // shop for real... $different_cart = new constructor_cart(/"20/", 17);