__construct() runs right after new allocates the object. With constructor property promotion (PHP 8.0), a parameter carrying a visibility keyword declares and assigns the property in one step. __destruct() runs the moment the last reference goes, or at shutdown for objects still alive.
<?php
class Order {
public function __construct(
public readonly int $id, // promoted: declared and assigned for you
private string $status = 'pending', // promoted with a default
string $note = '', // no visibility: an ordinary argument
) { echo "open #$id $note\n"; }
public function __destruct() { echo "close #{$this->id} ({$this->status})\n"; }
}
$a = new Order(5001, note: 'gift wrap');
$b = $a;
unset($a); // $b still holds the object
echo "after unset\n";
$b = null; // last reference gone: destructor runs now
echo "end of script\n";Output
open #5001 gift wrap after unset close #5001 (pending) end of script
Use destructors to release what the object holds, never for work that must happen, such as a commit. readonly is covered in Subsection 4.11.5.