PHP脚本可以在退出之前执行常规代码吗?

7
以下是如何在PHP脚本中实现类似以下内容的方法:

如何在PHP脚本中实现类似以下内容的方法?

 code{
      $result1 = task1() or break;
      $result2 = task2() or break;
 }

 common_code();
 exit();
3个回答

24
从PHP帮助文档中,你可以指定一个在exit()之后但脚本结束之前被调用的函数。
如有需要,请随时查阅文档以获取更多信息https://www.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');
?>

7

如果您使用面向对象编程(OOP),那么您可以将想要在退出时执行的代码放入类的析构函数中。

class example{
   function __destruct(){
      echo "Exiting";
   }
}

2

你的例子可能过于简单了,它可以很容易地被重写为以下形式:

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接