Constructors, Destructors and Property Promotion

3.Constructors, Destructors and Property Promotion

M

In this chapter

We'll learn how a constructor makes sure every object starts complete and valid, how constructor property promotion removes most of the boilerplate, how named constructors (static factory methods) give PHP several ways to create an object, what destructors do and when PHP calls them — and the features PHP doesn't have: constructor overloading and copy constructors.

15–17 min

The Problem in Real Life

The reminder log has a strange line: "Hi , your booking at is confirmed." Mia traces it to the walk-in screen: it creates new Booking(), then sets the customer and the start time a few lines later — except when Tom presses "Save" before typing the name.

The class allowed it. Nothing said "a booking needs a customer and a start time". A half-built booking went all the way to the SMS service.

M

A booking without a customer shouldn't even exist. Can the class refuse to be built like that?

Mia

Building Then Filling vs. Born Complete

Half-built objects

new Booking() followed by five assignments leaves a gap where the object exists but isn't complete.

Checked at birth

A constructor runs on every new. It can demand the values it needs and refuse bad ones.

More than one way to create

A walk-in and an online booking are created differently. Java uses several constructors; PHP uses named ones.

Constructors, Destructors and Property Promotion

Objects that start valid: the best moment to make sure an object is complete is the moment it's created. This chapter covers:

  • Constructors: the method that runs on new.
  • Constructor property promotion: declaring and setting properties in one line.
  • Named constructors: PHP's answer to constructor overloading.
  • Destructors: the method that runs when an object goes away.
  • Copy constructors: what C++ has, and what PHP uses instead.

Constructors: a method named __construct() is the class's constructor: PHP calls it automatically, once, every time new creates an object, and passes it the arguments written in new Booking(...). Its job is to make the new object complete and valid. Required values become required parameters, so new Booking() without a customer is an ArgumentCountError (Act 09) — the half-built booking from the walk-in screen can no longer be created. The constructor can also check values and refuse bad ones by throwing an exception (Act 14 explains exceptions properly): an empty customer name or a start time outside opening hours never becomes a Booking.

Mia's bug: an object can be used half-built
<?php
class Booking
{
public string $customer = "";
public string $start = "";
}
$booking = new Booking(); // exists, but empty
// ... Tom presses "Save" before typing the name ...
echo "Hi {$booking->customer}, your booking at {$booking->start} is confirmed.\n";
// Hi , your booking at is confirmed.
A constructor that demands and checks its values
<?php
declare(strict_types=1);
class Booking
{
public string $customer;
public string $start;
public function __construct(string $customer, string $start)
{
if (trim($customer) === "") {
throw new InvalidArgumentException("A booking needs a customer"); // Act 14
}
$this->customer = $customer;
$this->start = $start;
}
}
$booking = new Booking("Clare Lefèvre", "09:30");
echo "{$booking->customer} at {$booking->start}\n"; // Clare Lefèvre at 09:30
try {
new Booking("", "09:30");
} catch (InvalidArgumentException $e) {
echo "Refused: ", $e->getMessage(), "\n"; // Refused: A booking needs a customer
}
try {
new Booking();
} catch (ArgumentCountError $e) {
echo "Refused: missing arguments\n"; // Refused: missing arguments
}

Constructor property promotion: most constructors just copy parameters into properties: declare $customer, take $customer, write $this->customer = $customer; — three times for every property. Since PHP 8.0, constructor property promotion does it in one place: put the visibility word before a constructor parameter, public function __construct(public string $customer, public string $start) {}, and PHP declares the property and assigns it for you. Promoted parameters can have defaults and types like any parameter, and you can still write code in the constructor body, for checks. It's the usual style in modern PHP and in Laravel.

Constructor property promotion: the same class, shorter
<?php
declare(strict_types=1);
class Booking
{
public function __construct(
public string $customer,
public string $start,
public string $status = "pending", // promoted, with a default
) {
if (trim($customer) === "") {
throw new InvalidArgumentException("A booking needs a customer");
}
}
}
$booking = new Booking("Clare Lefèvre", "09:30");
echo "{$booking->customer} at {$booking->start}: {$booking->status}\n";
// Clare Lefèvre at 09:30: pending

Constructor overloading — not in PHP: Java and C# let a class have several constructors with different parameters: one for a walk-in (customer only), one for an online booking (customer, start time, barber). PHP doesn't support that: a class has exactly one __construct(). PHP covers the same need in two ways. Optional parameters and named arguments (Act 09) handle small differences. For really different ways of creating an object, use named constructors: public static methods that call new and return the object, like Booking::walkIn("Tom Hart") and Booking::online(...). Their names say what kind of booking you're making, which several unnamed constructors never could. (static methods are explained in chapter 5.)

Constructor overloading in Java (not in PHP)
// Java — two constructors, chosen by the arguments
class Booking {
final String customer;
final String start;
Booking(String customer) { // a walk-in: now
this(customer, "now");
}
Booking(String customer, String start) { // an online booking
this.customer = customer;
this.start = start;
}
}
new Booking("Tom Hart");
new Booking("Clare Lefèvre", "09:30");
PHP: named constructors instead
<?php
declare(strict_types=1);
class Booking
{
public function __construct(
public string $customer,
public string $start,
public string $source,
) {}
public static function walkIn(string $customer): static
{
return new static($customer, "now", "walk-in");
}
public static function online(string $customer, string $start): static
{
return new static($customer, $start, "online");
}
}
$a = Booking::walkIn("Tom Hart");
$b = Booking::online("Clare Lefèvre", "09:30");
echo "{$a->customer} ({$a->source}), {$b->customer} at {$b->start} ({$b->source})\n";
// Tom Hart (walk-in), Clare Lefèvre at 09:30 (online)

Destructors: a method named __destruct() is the destructor: PHP calls it when an object is about to disappear — when the last variable pointing to it is gone, for example when a function that created it returns, or when you set the variable to null — and at the latest at the end of the request (Act 10). PHP counts how many variables point to each object, so for most objects this happens at a predictable moment. Destructors are rarely needed in PHP; they're for releasing something outside PHP, like closing a file or a connection, and since PHP closes those at the end of every request anyway, most classes never have one. The diagram below shows an object's whole life.

The life of an object

new Booking("Clare Lefèvre", "09:30")

PHP reserves memory for a new object

at once

__construct() runs

checks and sets every property: the object is complete

then

The object is used

variables, arrays and other objects point at it

later

The last reference is gone

the variable is reassigned, the function returns, or the request ends

at once

__destruct() runs, memory is freed

the object no longer exists

When PHP calls a destructor
<?php
class Temp
{
public function __construct(public string $name)
{
echo "created {$this->name}\n";
}
public function __destruct()
{
echo "destroyed {$this->name}\n";
}
}
function preview(): void
{
$t = new Temp("preview");
echo "inside preview()\n";
} // $t goes away here
preview();
$receipt = new Temp("receipt");
$receipt = null; // the last reference is gone
echo "end of script\n";
// created preview
// inside preview()
// destroyed preview
// created receipt
// destroyed receipt
// end of script

Garbage collection and reference cycles: PHP keeps a count of how many variables point at each object, and frees the object the moment the count reaches zero — that's why destructors run at predictable times. There's one case the count can't handle: a reference cycle, where two objects point at each other (a Booking that knows its Customer, and a Customer that keeps a list of her bookings). Even when no variable outside points at them any more, each still counts one reference from the other, so neither reaches zero. For those, PHP has a garbage collector that runs from time to time, finds such cycles and frees them; gc_collect_cycles() runs it on demand. In a normal web request you never notice, because everything is freed at the end of the request anyway (Act 10); it matters for long-running scripts, like a worker that processes thousands of jobs.

A reference cycle, freed by the garbage collector
<?php
class Node
{
public ?Node $other = null;
public function __destruct()
{
echo "destroyed\n";
}
}
function makeCycle(): void
{
$booking = new Node();
$customer = new Node();
$booking->other = $customer; // they point at each other
$customer->other = $booking;
} // no destructor runs here: each still has one reference
makeCycle();
echo "after makeCycle()\n";
echo gc_collect_cycles(), " objects collected\n";
// after makeCycle()
// destroyed
// destroyed
// 2 objects collected

Copy constructors — not in PHP: C++ has copy constructors: a special constructor that runs when an object is copied, so the class decides how the copy is made. PHP doesn't have them. Instead, objects are copied with the clone keyword, and a class can customise the copy with a __clone() method — chapter 13 covers it, together with why assigning an object to a second variable doesn't copy it at all. The table below sums up the chapter.

Table — Creating and destroying objects
FeaturePHPOther languages
ConstructorOne __construct() per classJava, C#: any number (overloading)
Property promotionpublic string $x in the constructor (PHP 8.0)C# 12, Kotlin, TypeScript: similar primary constructors
Several ways to createNamed static constructors: Booking::walkIn()Java, C#: overloaded constructors
Destructor__destruct(), when the last reference is goneC++: same idea; Java, C#: no reliable equivalent
Copy constructorNot supported: clone + __clone()C++: supported

Key Takeaway

_construct() runs on every new and should make the object complete and valid: required values as required parameters, bad values refused. Constructor property promotion (public string $customer in the parameter list) declares and sets properties in one step. PHP has exactly one constructor per class — no constructor overloading — so use defaults, named arguments or named static constructors like Booking::walkIn(). destruct() runs when the last reference is gone; it's rarely needed. There are no copy constructors: use clone and _clone() (chapter 13).

Why This Matters

An object that can only be created complete and valid removes a whole category of bugs: code that receives a Booking never has to check whether it has a customer. The rule lives in one place — the constructor — instead of in every function that uses bookings.

Promotion and named constructors are everywhere in modern PHP and Laravel code. And knowing that PHP has one constructor per class — and why Booking::walkIn() exists — saves you from looking for constructor overloading that isn't there.

A Booking can no longer exist without a customer and a start time. But it can still be changed into nonsense afterwards: a line in the admin script does $booking->status = "confirmd"; and another sets $booking->pricePence = -500;. Every property is open to every line of code. That's the next chapter: visibility.