Breaking a parent function from within a child function (PHP Preferrably)

南笙酒味 提交于 2019-12-07 06:50:18

问题


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

回答1:


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



回答2:


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).



来源:https://stackoverflow.com/questions/3154489/breaking-a-parent-function-from-within-a-child-function-php-preferrably

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!