Web Analytics

PHP Constructors & Destructors

Intermediate~25 min read

Constructors initialize objects when they're created, and destructors clean up when they're destroyed. These special methods automate setup and teardown tasks!

Output
Click Run to execute your code

Constructor (__construct)

<?php
class User {
    public $name;
    
    public function __construct($name) {
        $this->name = $name;
        echo "User created: $name\n";
    }
}

$user = new User("Alice");  // Constructor called automatically
?>

Destructor (__destruct)

<?php
class User {
    public function __destruct() {
        echo "User destroyed\n";
    }
}
// Destructor called when script ends or object is unset
?>

Summary

  • __construct: Called when object created
  • __destruct: Called when object destroyed
  • Automatic: No manual calling needed
  • Use case: Initialize properties, cleanup resources

What's Next?

Next, learn about Access Modifiers - controlling visibility with public, protected, and private!