PHP Constructor and Destructor

PHP Constructor and Destructor

The constructor runs when an object is created; the destructor runs when it is destroyed or the script ends.

1 - Constructor

class Logger {
    private $handle;

    public function __construct(private string $path) {
        $this->handle = fopen($path, "a");
        if (!$this->handle) {
            throw new RuntimeException("Cannot open log file: $path");
        }
    }

    public function log(string $message): void {
        fwrite($this->handle, date("[Y-m-d H:i:s] ") . $message . PHP_EOL);
    }
}

2 - Constructor Promotion (PHP 8)

class Config {
    // Properties declared, assigned, and typed in one line
    public function __construct(
        public readonly string $appName,
        public readonly string $env = "production",
        public readonly bool   $debug = false
    ) {}
}

$cfg = new Config("MyApp", "local", true);
echo $cfg->appName; // MyApp

3 - Destructor

class DatabaseConnection {
    private PDO $pdo;

    public function __construct(string $dsn) {
        $this->pdo = new PDO($dsn, "root", "");
        echo "Connected.\n";
    }

    public function __destruct() {
        // PDO disconnects automatically when $pdo is garbage-collected
        echo "Connection closed.\n";
    }
}

{
    $db = new DatabaseConnection("mysql:host=localhost;dbname=app");
} // destructor fires here
echo "After block.";

Note: PHP 8.1 added readonly properties — once set in the constructor, they cannot be reassigned. This makes constructor-promoted readonly properties ideal for immutable value objects.

-Tip-