通常,你希望根据条件执行多于一条语句。当然,不需要给每条语句都加上 IF 判断。取而代之,可以把多条语句组成一个语句组。 If语句可以嵌套于其他 IF语句中,使你能够灵活地有条件的执行程序的各个部分。
2、 ELSE语句
通常你希望满足特定条件时执行一条语句,不满足条件是执行另一条语句。ELSE就是用来做这个的。ELSE 扩展IF语句,在IF语句表达式为FALSE时执行另一条语句。例如, 下面程序执行如果 $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,它扩展 IF 语句在IF表达式为 FALSE时执行其他的语句。但与ELSE不同,它只在ELSEIF表达式也为TRUE时执行其他语句。
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、 默认值
函数可以定义 C++ 风格的默认值,如下:
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. 注意,当使用默认参数时,所有有默认值的参数应在无默认值的参数的后边定义;否则,将不会按所想的那样工作。
5、CLASS(类)
类是一系列变量和函数的集合。类用以下语法定义:
<?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);