从循环内退出
我们不能在循环内使用 exit,因为它会完全停止运行程序的其余部分。
通常,我们只想停止执行循环的其余部分,为此我们可以使用 break 关键字。
但是,使用 break 关键字通常会增加在循环内使用条件逻辑的需要,这可能效率低下,具体取决于具体情况。
使用 break 关键字停止循环运行:
$i = '1'; while ($number <= '15') { break(); //Only the loop stops executing echo 'Run Number:' . $number . "\n"; ++$number; }
以下将不起作用:
$i = '1'; while ($number <= '15') { exit(); //The program exits on the first run without running any remaining code echo 'Run Number:' . $number . "\n"; ++$number; } //This code will not be executed, since we "exit" the script inside the loop
exit 通常在将最终输出发送到浏览器后立即使用,或者在出现错误时停止脚本。
当使用 exit 时,它将完全停止代码执行并退出 PHP。
当我们想将值发送回调用位置时,我们应该使用 return,并在我们希望 PHP 停止执行脚本的其余部分时退出。
以下是如何退出脚本的示例:
echo '<p>Hallo World</p>'; exit(); //Code past this point will not be executed //... more code here
当开发人员想要测试输出时,exit 通常用于快速和肮脏的错误搜索;完成后,输出通常与 echo、print、print_r 和 var_dump 一起发送。
有一个函数来输出变量的内容可能很常见:
function dumpText($variable) { header('content-type: text/plain; charset=utf-8'); var_dump($variable); exit(); }
另一个调用 exit 的常见位置是在发送位置标头重定向之后:
header('Location: https://onitroad.com/'); exit();
变量转储
变量转储非常适合学习变量内容的结构,这在调试和寻找错误时也很常见——但随着应用程序的增长,我们可能需要更复杂的错误处理。
通常,PHP 开发人员在调试应用程序时,会使用 var_dump 和 print_r 结合 exit 来输出变量和对象的内容。
这可以在脚本中的任何地方进行,甚至可以从面向对象的应用程序中的方法中进行。
这方面的一个例子是:
$my_array = array('bug', 'hunt', 'professionals'); $some_variable = 'test'; var_dump($some_variable); print_r($my_array); exit();
在全局范围内的某处声明一个函数更容易:
function dumpHTML($variable) { header('content-type: text/html; charset=utf-8'); var_dump($variable); exit(); }
从函数和方法调用退出
当一个函数或者方法被调用时,一旦执行完相关的函数代码,它通常会返回到调用脚本。
例如,如果我们从函数内部响应 HTTP 请求,通常需要让脚本停止执行任何剩余的代码。
IE。
:
function respond_not_found($code) { http_response_code(404); header('Content-Type: text/html; charset=UTF-8'); echo '<h1>404 Not Found</h1>' . '<p>Eh!? Now you are just guessing...</p>'; exit(); }
然后,当检查请求的页面时,我们可以简单地输出一个 404 并在找不到页面时退出:
$valid_system_pages_arr = array('frontpage' => true, 'categories' => true, 'blog' => true); if (isset($valid_system_pages_arr["$requested_page"]) == false) { respond_not_found(); } //The rest of our code goes here :-D echo 'A valid system page was requested.';