PHP – Break the parent function from the child function (preferably PHP)

Break the parent function from the child function (preferably PHP)… here is a solution to the problem.

Break the parent function from the child function (preferably PHP)

I was challenged how to use PHP to interrupt or end the execution of a parent function without modifying the parent function code

In addition to die(); I can’t think of any solution; In child, this will end all executions, so anything after the parent function call will end. Any ideas?

Code sample:

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

Solution

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

Related Problems and Solutions