0% complete

Object-Oriented PHP · Lesson 7 of 14

Destructors

Understand object cleanup and prefer explicit resource management.

Lesson

The __destruct method may run when an object is no longer referenced or during shutdown. Its timing is not a substitute for explicit resource management, especially when cleanup must happen predictably. Use try/finally or a resource abstraction for important cleanup; do not rely on destructors to commit critical work. Destructors are most appropriate for releasing resources owned by an object. Further guidance Give an object one clear responsibility and protect state that must satisfy a rule. Prefer a small public contract and composition for replaceable collaborators; use inheritance only for a genuine subtype. Test behavior through public methods instead of relying on internal implementation details. Practice task: Create a fresh example for Destructors. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Destructors
PHP
class TemporaryNotice
{
    public function __destruct()
    {
        echo 'Object released';
    }
}
$notice = new TemporaryNotice();
unset($notice);
Expected output
Object released

Key points

  • Understand object cleanup and prefer explicit resource management.
  • Protect object invariants behind a small public API.
  • Prefer composition unless inheritance expresses a genuine subtype.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.