# 流程控制 * * * * * > 任何 PHP 脚本都是由一系列语句构成的。一条语句可以是一个赋值语句,一个函数调用,一个循环,一个条件语句或者甚至是一个什么也不做的语句(空语句)。语句通常以分号结束。此外,还可以用花括号将一组语句封装成一个语句组。语句组本身可以当作是一行语句。本章介绍了各种语句类型。 Table of Contents if else elseif/else if 流程控制的替代语法 while do-while for foreach break continue switch declare return require include require_once include_once goto * * * * * **if** ~~~ <?php if ( $a > $b ) echo "a is bigger than b" ; ?> ~~~ **else** ~~~ if ( $a > $b ) { echo "a is greater than b" ; } else { echo "a is NOT greater than b" ; } ~~~ **elseif/else if** ~~~ if ( $a > $b ) { echo "a is bigger than b" ; } elseif ( $a == $b ) { echo "a is equal to b" ; } else { echo "a is smaller than b" ; } ~~~ **流程控制的替代语法** ~~~ <?php if ( $a == 5 ): ?> A is equal to 5 <?php endif; ?> ~~~ **while** ~~~ $i = 1 ; while ( $i <= 10 ) { echo $i ++; /* the printed value would be $i before the increment (post-increment) */ } ~~~ **do-while** ~~~ $i = 0 ; do { echo $i ; } while ( $i > 0 ); ~~~ **for** ~~~ for ( $i = 1 ; $i <= 10 ; $i ++) { echo $i ; } ~~~ **foreach** ~~~ foreach (array( 1 , 2 , 3 , 4 ) as & $value ) { $value = $value * 2 ; } ~~~ **break** ~~~ switch ( $i ) { case '1': // Works echo "$i=1"; break; case '2': // Works require( 'include1.inc' ); break; case '3': // Doesn't work require( 'include2.inc' ); break; case '4': // Doesn't work, same reason require( 'include2.inc' ); default: // Works echo "$i"; } ~~~ **continue** ~~~ for ( $i = 0 ; $i < 5 ; ++ $i ) { if ( $i == 2 ) continue print " $i \n" ; } ~~~ **switch** ~~~ switch ( $i ) { case "apple" : echo "i is apple" ; break; case "bar" : echo "i is bar" ; break; case "cake" : echo "i is cake" ; break; } ~~~ **declare** ~~~ // these are the same: // you can use this: declare( ticks = 1 ) { // entire script here } // or you can use this: declare( ticks = 1 ); // entire script here ~~~ **return** 如果在一个函数中调用 return 语句,将立即结束此函数的执行并将它的参数作为函数的值返回。 **require** **include** ~~~ vars.php <?php $color = 'green' ; $fruit = 'apple' ; ?> test.php <?php echo "A $color $fruit " ; // A include 'vars.php' ; echo "A $color $fruit " ; // A green apple ?> ~~~ **require_once** **include_once** ~~~ include_once "a.php" ; // 这将包含 a.php include_once "A.php" ; // 这将再次包含 a.php!(仅 PHP 4) ~~~ **goto** ~~~ goto a ; echo 'Foo' ; a : echo 'Bar' ; ~~~ > goto 操作符仅在 PHP 5.3及以上版本有效。