问题
This is a little difficult to explain, but i'll try my best.
This is similar to the code i'm currently running.
function func1()
{
func2()
}
function func2()
{
exit();
}
I need to be able to stop the execution of func1 from within func2, but I need a better way to do it than exit(). Since the caller of func1 might have other operations to do, I don't want to stop them as well, I just want to stop the rest of func1 from executing.
I'm aware that I could put a simple if statement in func1 to detect the return value of func2 and then return if it's a certain value, but that's a bit messy too.
So my question is, how can I stop the execution of the remainder of the caller function, from within a function?
回答1:
Return a value and check for it.
function func1()
{
$result = func2();
if ($result === 0) return;
// Your func1 code here
}
function func2()
{
if ( ... ) return 1;
else return 0;
}
回答2:
Checking a return value isn't messy. It's standard practice. You basically have two options:
- Check return values.
- Throw an exception in func2. If it's uncaught in func1 it'll bubble up higher and stop execution in both functions.
回答3:
There is absolutely no way this will work.
Remember: func2()
could be called from ANYWHERE, not only func1()
. How would you know that it is func1 you are stopping.
Whatever it is that made you think interrupting the calling function would solve the problem - think again, and tell us about the bigger picture for proper advice.
来源:https://stackoverflow.com/questions/19368937/php-stopping-the-execution-of-the-calling-function