Constructors and Destructors
Initialize objects with __construct and clean up with __destruct.
Constructors and Destructors is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction: Constructors and Destructors
The __construct() method runs automatically when a new object is created. The __destruct() method runs when the object is garbage collected. PHP 8 introduced constructor property promotion.
Core Concepts
Constructors and Destructors key concepts:
__construct()initializes the object- Constructor property promotion shortens code
__destruct()for cleanup (file handles, connections)- Parent constructor called with
parent::__construct()
Basic Constructor
Example:
<?php
class User {
public string $name;
public string $email;
public function __construct(string $name, string $email) {
$this->name = $name;
$this->email = $email;
}
}
$user = new User('Alice', 'alice@example.com');
echo $user->name; // AliceConstructor Promotion (PHP 8)
Continued:
<?php
class User {
// Shorthand: declare and assign in one go
public function __construct(
public readonly string $name,
public readonly string $email,
private int $loginCount = 0,
) {}
}
$u = new User('Bob', 'bob@test.com');
echo $u->name; // BobValidation in Constructor
Practice:
<?php
class PositiveInt {
public function __construct(private int $value) {
if ($value <= 0) {
throw new InvalidArgumentException(
"Value must be positive, got $value"
);
}
}
public function get(): int { return $this->value; }
}
$n = new PositiveInt(5); // OK
// new PositiveInt(-1); // throwsDestructor
Deeper:
<?php
class FileLogger {
private mixed $handle;
public function __construct(string $path) {
$this->handle = fopen($path, 'a');
}
public function log(string $msg): void {
fwrite($this->handle, date('c') . ' ' . $msg . PHP_EOL);
}
public function __destruct() {
if ($this->handle) fclose($this->handle);
echo 'File handle released';
}
}Named Constructor Pattern
Advanced usage:
<?php
class Money {
private function __construct(
private float $amount,
private string $currency
) {}
public static function usd(float $a): self { return new self($a, 'USD'); }
public static function eur(float $a): self { return new self($a, 'EUR'); }
public function format(): string {
return number_format($this->amount, 2) . ' ' . $this->currency;
}
}
echo Money::usd(9.99)->format(); // 9.99 USDParent Constructor
Real-world pattern:
<?php
class Animal {
public function __construct(
protected string $name,
protected string $sound
) {}
}
class Dog extends Animal {
public function __construct(string $name) {
parent::__construct($name, 'Woof');
}
public function speak(): string {
return "{$this->name} says {$this->sound}!";
}
}
echo (new Dog('Rex'))->speak(); // Rex says Woof!Late Static Binding in Constructors
Best practices:
<?php
class Base {
public static function create(): static {
return new static(); // 'static' resolves to calling class
}
}
class Child extends Base {}
$base = Base::create(); // Base object
$child = Child::create(); // Child object — static binding worksPractical Pattern
Putting it all together with a practical pattern for Constructors and Destructors.
Common Pitfalls
Avoid these common mistakes with Constructors and Destructors:
- Always call parent::__construct() when extending a class
- Use constructor promotion in PHP 8+ to reduce boilerplate
- Destructor is not guaranteed to run at a specific time
- Prefer named constructors over multiple __construct() overloads
Quick Check
What is constructor property promotion in PHP 8?
Recap: Constructors and Destructors
You've covered Constructors and Destructors. Key points to remember:
- Always call parent::__construct() when extending a class
- Use constructor promotion in PHP 8+ to reduce boilerplate
- Destructor is not guaranteed to run at a specific time
- Prefer named constructors over multiple __construct() overloads
Frequently asked questions
Is the “Constructors and Destructors” lesson free?
Yes — the full text of “Constructors and Destructors” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Constructors and Destructors”?
Initialize objects with __construct and clean up with __destruct. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Constructors and Destructors” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Classes, Properties, and Methods
- Constructors and Destructors
- Static Properties and Methods
- Magic Methods Overview