The constructor runs when an object is created; the destructor runs when it is destroyed or the script ends.
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);
}
}
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
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.";