【发布时间】:2010-11-29 00:02:52
【问题描述】:
如何在 PHP 脚本中完成以下操作?
code{
$result1 = task1() or break;
$result2 = task2() or break;
}
common_code();
exit();
【问题讨论】:
如何在 PHP 脚本中完成以下操作?
code{
$result1 = task1() or break;
$result2 = task2() or break;
}
common_code();
exit();
【问题讨论】:
如果您使用 OOP,那么您可以将要在退出时执行的代码放入类的析构函数中。
class example{
function __destruct(){
echo "Exiting";
}
}
【讨论】:
从 PHP 帮助文档中,您可以指定在 exit() 之后但在脚本结束之前调用的函数。
请随时查看文档以获取更多信息http://us3.php.net/manual/en/function.register-shutdown-function.php
<?php
function shutdown()
{
// This is our shutdown function, in
// here we can do any last operations
// before the script is complete.
echo 'Script executed with success', PHP_EOL;
}
register_shutdown_function('shutdown');
?>
【讨论】:
您的示例可能过于简单,因为它可以很容易地重写如下:
if($result1 = task1()) {
$result2 = task2();
}
common_code();
exit;
也许您正在尝试像这样构建流控制:
do {
$result1 = task1() or break;
$result2 = task2() or break;
$result3 = task3() or break;
$result4 = task4() or break;
// etc
} while(false);
common_code();
exit;
您也可以使用switch():
switch(false) {
case $result1 = task1(): break;
case $result2 = task2(): break;
case $result3 = task3(): break;
case $result4 = task4(): break;
}
common_code();
exit;
或者在 PHP 5.3 中你可以使用goto:
if(!$result1 = task1()) goto common;
if(!$result2 = task2()) goto common;
if(!$result3 = task3()) goto common;
if(!$result4 = task4()) goto common;
common:
echo "common code\n";
exit;
【讨论】: