从子函数中中断父函数(最好是 PHP)

发布于 09-07 13:49 字数 344 浏览 8 评论 0原文

我面临的挑战是如何在不修改父函数代码的情况下中断或结束父函数的执行,使用 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";

I was challenged how to break or end execution of a parent function without modifying the code of the parent, using PHP

I cannot figure out any solution, other than die(); in the child, which would end all execution, and so anything after the parent function call would end. Any ideas?

code example:

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";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

琉璃繁缕2024-09-14 13:49:23
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";
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";
习ぎ惯性依靠2024-09-14 13:49:23

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

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() 正常完成(仅当您确实将脚本作为错误处理程序的一部分终止时)。

Note that Exceptions are not going to work in the following scenario:

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();

You would need something else, the only thing more robust would be something like installing your own error handler, ensure all errors are reported to the error handler and ensure errors are not converted to exceptions; then trigger an error and have your error handler kill the script when done. This way you can execute code outside of the context of killer()/victim() and prevent victim() from completing normally (only if you do kill the script as part of your error handler).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文