5

我受到挑战如何使用 PHP 在不修改父代码的情况下中断或结束父函数的执行

我想不出任何解决方案,除了 die(); 在孩子中,这将结束所有执行,因此父函数调用之后的任何事情都将结束。有任何想法吗?

代码示例:

function victim() {
    echo "I should be run";
    killer();
    echo "I should not";
}
function killer() {
    //code to break parent here
}
victim();
echo "This should still run";
4

2 回答 2

7
function victim() {
    echo "I should be run";
    killer();
    echo "I should not";
}
function killer() {
    throw new Exception('Die!');
}

try {
    victim();
} catch (Exception $e) {
    // note that catch blocks shouldn't be empty :)
}
echo "This should still run";
于 2010-07-01T01:07:08.773 回答
0

请注意,异常在以下情况下不起作用:

function victim() {
  echo "this runs";
  try {
    killer();
  }
  catch(Exception $sudden_death) {
    echo "still alive";
  }
  echo "and this runs just fine, too";
}

function killer() { throw new Exception("This is not going to work!"); }

victim();

您将需要其他东西,唯一更强大的是安装您自己的错误处理程序,确保将所有错误报告给错误处理程序并确保错误不会转换为异常;然后触发错误并让您的错误处理程序在完成后终止脚本。这样,您可以在killer()/victim() 的上下文之外执行代码并防止victim() 正常完成(仅当您确实将脚本作为错误处理程序的一部分终止时)。

于 2010-07-01T03:06:48.617 回答