Typed Properties, Promotion and Readonly, Revisited

1.Typed Properties, Promotion and Readonly, Revisited

M

In this chapter

We'll revisit typed properties, constructor promotion and readonly with the rules Act 11 skipped: which types a property may have, the difference between null and "not set yet", how promoted and readonly properties combine, what a readonly class forbids — and how C#'s required and init members and Kotlin's lateinit compare.

13–15 min

The Problem in Real Life

Tuesday, 15 days before launch. Over the weekend the server was upgraded to PHP 8.5, and on Monday morning two things showed up. The error log is full of one line, repeated thousands of times: "Deprecated: Creation of dynamic property Booking::$note". And a booking in the database has the status "confirmd".

"Modern PHP has a tool for both," says Marcus. "This week we make wrong values impossible instead of just unlikely." First, though, the bookings page crashes for every booking without a discount: "Typed property Booking::$discountPence must not be accessed before initialization".

M

No discount means null. Why does PHP say the property was never set?

Mia

Not Set Yet vs. Set to Nothing

null is a value

A typed property without a default isn't null — it has no value at all until something sets it.

Types on data

Property types work like parameter types — with a few types that only make sense for functions left out.

Set once, by the right code

Readonly and promotion together give data that's complete at birth and never changes afterwards.

Typed Properties, Promotion and Readonly, Revisited

Modern PHP OOP: Act 11 taught classes the way they work in every object-oriented language. This Act covers what modern PHP adds — enums, property hooks, attributes and more. It starts by tightening what you already use:

  • Typed properties: the full rules, and the difference between null and uninitialized.
  • Promotion and readonly together: complete, immutable objects in a few lines.
  • Readonly classes: what they allow and what they forbid.
  • Required and init-only members: how C# and Kotlin do it, and PHP's equivalent.

Which types a property may have: a property accepts the same types as a parameter (Act 09) — scalars, array, class and interface names, nullable ?T, unions like int|float, mixed, self — with three exceptions. void and never describe what a function returns, so they make no sense for data. And callable isn't allowed, because whether something is callable depends on where it's called from; use Closure instead. With strict_types on in the file that assigns the value, a wrong type is a TypeError; without it, PHP converts what it can, as for parameters.

Types a property can't have
<?php
class Booking
{
public callable $onConfirm;
}
// Fatal error: Property Booking::$onConfirm cannot have type callable
// Use Closure instead: public Closure $onConfirm;

null versus uninitialized: a typed property with a default starts with that value. A typed property without a default starts uninitialized: not null, but no value at all, and reading it is an Error (Act 11). Even a nullable type doesn't change that: public ?int $discountPence; is uninitialized, not null. That's Mia's crash: bookings created without a discount never assigned the property, and the page read it. If "no discount" is a real, valid state, say so: public ?int $discountPence = null;. If every booking must have a value, set it in the constructor. Untyped properties (public $note;) are the old style; they default to null and accept anything — avoid them in new code. The diagram below shows the states a typed property goes through.

The states of a typed property

public ?int $discountPence;

declared, no default

after new

Uninitialized

no value at all — reading it is an Error

first assignment

Has a value

null, 0 or 500 — reading works

after that

readonly: locked

any further write is an Error

not readonly: can change

type still checked on every write

Mia's crash: ?int without a default is not null
<?php
declare(strict_types=1);
class Booking
{
public ?int $discountPence; // nullable, but no default: uninitialized
}
class FixedBooking
{
public ?int $discountPence = null; // "no discount" is a real state: say so
}
try {
var_dump((new Booking())->discountPence);
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
var_dump((new FixedBooking())->discountPence);
// Typed property Booking::$discountPence must not be accessed before initialization
// NULL

Promotion and readonly together: constructor promotion (Act 11) and readonly combine into the shortest way to write a complete, immutable object: public function __construct(public readonly string $customer, public readonly Money $price) {}. Everything is required at new, typed, set exactly once, and never changes. Promoted parameters can have defaults, and you can mix promoted and normal parameters. A readonly property must have a type and can't have a default value outside the constructor; to make a changed copy, use PHP 8.5's clone($this, [...]) from inside the class (Act 11).

Promotion and readonly together
<?php
declare(strict_types=1);
final class Booking
{
public function __construct(
public readonly string $customer,
public readonly string $start,
public readonly ?int $discountPence = null, // optional, still readonly
) {}
}
$b = new Booking("Clare Lefèvre", "09:30");
echo $b->customer, " at ", $b->start, ", discount: ", $b->discountPence ?? "none", "\n";
// Clare Lefèvre at 09:30, discount: none
try {
$b->start = "11:00";
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Cannot modify readonly property Booking::$start
}

new in initializers: since PHP 8.1, a parameter's default value can create an object with new: public function __construct(public Money $price = new Money(2500)) {}. Before, defaults could only be constants, so code wrote ?Money $price = null and then $this->price = $price ?? new Money(2500); inside — two lines and a nullable type for something that's never really null. The same works in attribute arguments (chapter 8) and static variables. Each call that leaves the argument out gets its own new object, created at call time.

new in initializers (PHP 8.1)
<?php
declare(strict_types=1);
final readonly class Money
{
public function __construct(public int $pence = 0) {}
}
final class Booking
{
public function __construct(
public string $customer,
public Money $price = new Money(2500), // an object as a default value
) {}
}
echo (new Booking("Tom Hart"))->price->pence, "\n"; // 2500
echo (new Booking("Ann Lee", new Money(1000)))->price->pence, "\n"; // 1000

Readonly classes: readonly class Money { ... } (PHP 8.2) makes every declared property readonly — and it does more. Every property must have a type, there can be no static properties, and no dynamic properties at all: writing an undeclared property on a readonly object is an Error ("Cannot create dynamic property"), not a deprecation. That's one of the ways to make the deprecation from Mia's log impossible (chapter 7 shows the others). A class that extends a readonly class must be readonly too.

A readonly class forbids dynamic properties outright
<?php
declare(strict_types=1);
readonly class Money
{
public function __construct(public int $pence) {}
}
$price = new Money(2750);
try {
$price->currency = "GBP"; // not declared
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Cannot create dynamic property Money::$currency
}

Required and init-only members — not as such in PHP: C# has required properties, which every object initializer must set, and init accessors, which may be set only while the object is being created. Kotlin has lateinit var, a non-null property that is promised to be set later and fails if read before — which is exactly how PHP's uninitialized typed properties behave. PHP doesn't have required or init keywords. Its equivalent is the constructor: required values are required constructor parameters, and "set only during creation" is readonly. The table below sums up the states a property can be in.

Table — The states of a property
Declared asStarts asReading before assignment
public $note;null (untyped)null
public ?int $discountPence = null;nullnull
public ?int $discountPence;UninitializedError: must not be accessed before initialization
public string $customer;UninitializedError
public readonly string $customer;Uninitialized; set onceError
Promoted: __construct(public string $customer)Set by the constructorAlways set
C#: required and init (PHP uses the constructor)
// C# 11 — required members must be set; init members only while creating the object
public class Booking
{
public required string Customer { get; init; }
public string Start { get; init; } = "09:00";
}
var b = new Booking { Customer = "Clare Lefèvre", Start = "09:30" };
// b.Start = "11:00"; // compile error: init-only
// new Booking { }; // compile error: Customer is required
// PHP: __construct(public readonly string $customer, public readonly string $start = "09:00")

Key Takeaway

Properties take the same types as parameters except void, never and callable (use Closure). A typed property without a default is uninitialized — not null — and reading it is an Error, even for ?int; write = null when "no value" is valid. Promotion plus readonly gives complete, immutable objects in one line. A readonly class makes every property readonly, requires types and forbids dynamic properties entirely. PHP has no required or init keywords (C#); required constructor parameters and readonly do that job, and uninitialized properties behave like Kotlin's lateinit.

Why This Matters

The difference between null and "not set yet" decides whether a missing value is a normal case or a bug, and PHP lets you say which. Writing = null on purpose — or requiring the value in the constructor — turns a crash on some bookings into a decision you made once.

Readonly, promotion and readonly classes are the backbone of the modern classes in the rest of this Act: enums, value objects and data objects that can't drift into impossible states.

$discountPence now defaults to null, and the bookings page loads. Next, the misspelled status. The status is still a plain string, so "confirmd", "Confirmed" and "CONFIRMED" are all accepted, and a report that counts confirmed bookings misses three of them. PHP has had a type for "one of these exact values" since 8.1. That's the next chapter: enums.