In PHP, handling memory exhaustion errors requires a multifaceted approach. While increasing the memory limit with ini_set() may seem a quick fix, it's not always feasible or desirable.
One recommended method involves using register_shutdown_function() along with error_get_last(). This allows you to check for errors at script shutdown and capture the null value if no error occurred.
<code class="php">register_shutdown_function(function(){ $error = error_get_last(); if(null !== $error) { echo 'Caught at shutdown'; } });</code>
In your gateway script, consider using try/catch blocks to capture fatal errors:
<code class="php">try { while(true) { $data .= str_repeat('#', PHP_INT_MAX); } } catch(\Exception $exception) { echo 'Caught in try/catch'; }</code>
However, in this example, the ErrorException object isn't thrown fully due to premature script termination.
Finally, disable error display by setting display_errors to false and check the error array in the shutdown function to ascertain the error cause and respond appropriately.
These techniques provide a safe and flexible way to handle memory exhaustion errors in PHP without resorting to excessive memory limit increases.
The above is the detailed content of Can PHP Handle Memory Exhaustion Errors Without Exceeding Memory Limits?. For more information, please follow other related articles on the PHP Chinese website!