PHP中类析构函数不被调用的脚本终止场景有哪些?
Great question—ensuring your cleanup code runs reliably is super important, especially when dealing with resources like file handles, database connections, or locks. Let’s break down the key scenarios where user-defined destructors won’t execute when a script terminates, along with contrasting cases where they do work as expected:
Destructors Will NOT Be Called
These are cases where the runtime or operating system cuts off execution immediately, leaving no time for cleanup routines:
- Fatal interpreter errors: Things like segmentation faults (
SIGSEGV), invalid memory access, or using a broken extension that crashes the VM. The interpreter can’t safely proceed to run destructors in this state. - Forced termination via
SIGKILL: The OS sends this signal to immediately kill the process—no signal handling or cleanup code gets a chance to run. This is different fromSIGTERM, which allows graceful shutdown. - OS-initiated out-of-memory (OOM) kills: If your process consumes too much memory and the kernel terminates it to save the system, there’s no opportunity for the runtime to execute destructors.
- Low-level immediate exit calls: Using system-level functions like
_exit()(instead of the standard languageexit()), which bypass the runtime’s shutdown sequence entirely. - Hard system failures: Power loss, kernel panics, or hardware crashes will stop the process instantly, with no cleanup possible.
Destructors Will Be Called
These are scenarios where the runtime gets a chance to properly shut down and run cleanup code:
- Unhandled exceptions: Even if an uncaught exception terminates the script, most languages will still trigger destructors for objects that were in scope before the exception occurred.
- Graceful signals: Signals like
SIGTERM(sent bykillcommand by default) orSIGINT(Ctrl+C) are typically caught by the runtime, which then proceeds to run shutdown routines including destructors. - Normal script completion: When the script finishes executing all code, destructors are called as objects go out of scope or the runtime cleans up its environment.
- Standard
exit()/die()calls: Most high-level language exit functions trigger the runtime’s shutdown process, which includes running destructors for existing objects.
Quick Note on Critical Cleanup
If you have cleanup tasks that absolutely must run (e.g., releasing a shared lock), keep in mind that some scenarios (like SIGKILL or OOM kills) are unavoidable. For these cases, consider:
- Using signal handlers to catch catchable signals and trigger cleanup before exiting.
- Adding checks in your next script run to detect leftover resources and clean them up.
- Using process supervision tools to monitor your script and handle failures gracefully.
内容的提问来源于stack exchange,提问作者Zhigalin

