If you use XDebug, there is a maximum function nesting depth which is controlled by an ini setting:
$foo = function() use (&$foo) {
$foo();
};
$foo();
Produces the following error:
Fatal error: Maximum function nesting level of '100' reached, aborting!
This IMHO is a far better alternative than a segfault, since it only kills the current script, not the whole process.
There is this thread that was on the internals list a few years ago (2006). His comments are:
So far nobody had proposed a solution for endless loop problem that
would satisfy these conditions:
- No false positives (i.e. good code always works)
- No slowdown for execution
- Works with any stack size
Thus, this problem remains unsloved.
Now, #1 is quite literally impossible to solve due to the halting problem. #2 is trivial if you keep a counter of stack depth (since you're just checking the incremented stack level on stack push).
Finally, #3 Is a much harder problem to solve. Considering that some operating systems will allocate stack space in a non-contiguous manner, it's not going to be possible to implement with 100% accuracy, since it's impossible to portably get the stack size or usage (for a specific platform it may be possible or even easy, but not in general).
Instead, PHP should take the hint from XDebug and other languages (Python, etc) and make a configurable nesting level (Python's is set to 1000 by default)....
Either that, or trap memory allocation errors on the stack to check for the segfault before it happens and convert that into a RecursionLimitException
so that you may be able to recover....
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…