php 中 return exit break contiue 详解

发布时间:2013-9-25 15:52    发布者:reggae
关键词: php
return、break和contiue是语言结构,就如同if语句之类的,但是exit却是个函数。

1.exit函数
作用:Output a message and terminate the current script
输出一则消息并且终止当前脚本。
如果一段文本中包括多个以 结束的脚本,exit退出所有脚本。
比如一篇php文本包括一下代码,则不输出为world。
  1. echo "hello";
  2. exit;
  3. ?>
  4. echo "world";
  5. ?>
复制代码

语法格式:void表示没有返回值。
void exit ([ string $status ] )
void exit ( int $status )
If status is a string, this function prints the status just before exiting.
如果status是一段字符串,这个函数在脚本退出前打印status。
If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
如果status是一个整数,这个整数会被作为退出状态。退出状态应该从0到254,退出状态255被PHP保留并禁止使用。状态0被用来表示成功的终止程序。

2.return语言结构的用法

作用:终止函数的执行和从函数中返回一个值

3.break和continue

用在for,foreach,while,do..while 或者 switch 结构中。

break 结束当前 for,foreach,while,do..while 或者 switch 结构的执行。

break 可以接受一个可选的数字参数来决定跳出几重循环。

代码:

  1. $arr = array ('one', 'two', 'three', 'four', 'stop', 'five');
  2. while (list (, $val) = each ($arr)) {
  3. if ($val == 'stop') {
  4. break;
  5. }
  6. echo "$val
    \n";
  7. }


  8. $i = 0;
  9. while (++$i) {
  10. switch ($i) {
  11. case 5:
  12. echo "At 5
    \n";
  13. break 1;
  14. case 10:
  15. echo "At 10; quitting
    \n";
  16. break 2;
  17. default:
  18. break;
  19. }
  20. }
  21. ?>
复制代码

continue 在循环结构用用来跳过本次循环中剩余的代码并开始执行本循环结构的下一次循环。

注: 注意在 PHP 中 switch 语句被认为是作为 continue 目的的循环结构。

continue 接受一个可选的数字参数来决定跳过几重循环到循环结尾。

代码:

  1. while (list ($key, $value) = each ($arr)) {
  2. if (!($key % 2)) { // skip odd members
  3. continue;
  4. }
  5. do_something_odd ($value);
  6. }

  7. $i = 0;
  8. while ($i++ < 5) {
  9. echo "Outer
    \n";
  10. while (1) {
  11. echo " Middle
    \n";
  12. while (1) {
  13. echo " Inner
    \n";
  14. continue 3;
  15. }
  16. echo "This never gets output.
    \n";
  17. }
  18. echo "Neither does this.
    \n";
  19. }
  20. ?>
复制代码
以上是本文关于php 中 return exit break contiue 的详解,希望本文对广大php开发者有所帮助,感谢阅读本文。更多php技术问题欢迎加群探讨:256271784,验证码:eec,不写验证不予通过哟~

本文地址:https://www.eechina.com/thread-121347-1-1.html     【打印本页】

本站部分文章为转载或网友发布,目的在于传递和分享信息,并不代表本网赞同其观点和对其真实性负责;文章版权归原作者及原出处所有,如涉及作品内容、版权和其它问题,我们将根据著作权人的要求,第一时间更正或删除。
您需要登录后才可以发表评论 登录 | 立即注册

厂商推荐

关于我们  -  服务条款  -  使用指南  -  站点地图  -  友情链接  -  联系我们
电子工程网 © 版权所有   京ICP备16069177号 | 京公网安备11010502021702
快速回复 返回顶部 返回列表