【转】PHP帮助手册拾遗二:流程控制
时间:2010-11-03 来源:wingle
1、PHP支持用冒号的if语句
          1 2 3 4 5  | 
        
          if (expr1) : statement1 elseif(expr2): statement2 endif;  | 
      
endif后面有分号
2、PHP 也支持用冒号的 for 循环的替代语法。
          1 2 3 4  | 
        
          for (expr1; expr2; expr3): statement; ... endfor;  | 
      
很python的作法,只是还是需要加上endfor作为结束标记
          1 2 3  | 
        
          for ($i = 0; $i < 10; $i++): echo $i, '<br />'; endfor;  | 
      
  3、foreach PHP 5 起,可以很容易地通过在 $value 之前加上 & 来修改数组的单元。此方法将以引用赋值而不是拷贝一个值。
  如下所示代码:
          1 2 3 4 5 6 7 8  | 
        
          $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } //unset($value); // 释放$value的引用 var_dump($arr); $value++; var_dump($arr);  | 
      
只是在写修改完后,需要释放$value的引用,否则在下次修改此变量时,会改变数组元素的内容,慎重!(某犯过此错误)
4、break 可以接受一个可选的数字参数来决定跳出几重循环。
          1 2 3 4 5 6 7 8 9 10 11  | 
        
          for ($i = 1; $i < 10; $i++) : for ($j = 1; $j < 10; $j++) : echo $i, ' ', $j, '<br />'; if ($i + $j > 15) { break 2; // 直接跳转所在的二重循环 } endfor; endfor;  | 
      
  5、注意在 PHP 中 switch 语句被认为是可以使用 continue 的一种循环结构。
  6、continue 接受一个可选的数字参数来决定跳过几重循环到循环结尾。
  7、在 switch 语句中条件只求值一次并用来和每个 case 语句比较。在 elseif 语句中条件会再次求值。
  case 表达式可以是任何求值为简单类型的表达式,即整型或浮点数以及字符串。不能用数组或对象,除非它们被解除引用成为简单类型。
  8、declare 结构用来设定一段代码的执行指令。declare 的语法和其它流程控制结构相似
  directive 部分允许设定 declare 代码段的行为。目前只认识一个指令:ticks
  Tick 是一个在 declare 代码段中解释器每执行 N 条低级语句就会发生的事件。N 的值是在 declare 中的 directive 部分用 ticks=N 来指定的。
  在每个 tick 中出现的事件是由 register_tick_function() 来指定的。
  Ticks 很适合用来做调试,以及实现简单的多任务,后台 I/O 和很多其它任务。
  手册上的示例:
          1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29  | 
        
          function profile($dump = FALSE) { static $profile; // Return the times stored in profile, then erase it if ($dump) { $temp = $profile; unset($profile); return ($temp); } $profile[] = microtime(); } // Set up a tick handler register_tick_function("profile"); // Initialize the function before the declare block profile(); // Run a block of code, throw a tick every 2nd statement declare(ticks=2) { for ($x = 1; $x < 50; ++$x) { echo similar_text(md5($x), md5($x*$x)), "<br />;"; } } // Display the data stored in the profiler print_r(profile (TRUE));  | 
      
上面的这功能真没听说过,作为一个后学末进的程序员,看手册是必须的。
  10、return
  return() 是语言结构而不是函数,仅在参数包含表达式时才需要用括号将其括起来。当返回一个变量时通常不用括号,也建议不要用,这样可以降低 PHP 的负担。
  注: 当用引用返回值时永远不要使用括号,这样行不通。只能通过引用返回变量,而不是语句的结果。如果使用 return ($a); 时其实不是返回一个变量,而是表达式 ($a) 的值(当然,此时该值也正是 $a 的值)。
  11、include() 是一个特殊的语言结构,其参数不需要括号。在比较其返回值时要注意。
  例如,test.txt中包含字符串 ‘abc’,则判断包含test.txt中是否返回’abc’语句不能以函数的调用方式。
  如下所示代码:
          1 2 3 4 5 6 7 8  | 
        
          if (include("test.txt") == 'abc') { echo 'yes'; } /* 以上是错误的代码,程序会执行错误,显示warning */ if ((include "test.txt") == 'abc') { echo 'yes'; }  | 
      
12、从PHP3.0开始添加了goto语句,但是此语句不能跳转进入loop或switch 语句
Copyright 2006-2020 (phpxiu.com) All Rights Reserved.
本站为非盈利性网站,不接受任何广告。php爱好者










