Anonymous Classes and final

3.Anonymous Classes and final

M

In this chapter

We'll learn anonymous classes — classes without a name, written right where one object is needed — why they're perfect for test doubles, how final classes, methods and constants protect a design, why many teams make classes final by default, and how this compares with Java's anonymous and local classes and JavaScript's object literals.

12–14 min

The Problem in Real Life

Mia writes tests for the confirmation code. Each test needs a fake Notifier (Act 11) that records messages instead of sending them, so each test file declares a tiny class FakeNotifier.

Running the tests one at a time works. Running them all at once stops at the second file: "Cannot redeclare class FakeNotifier". Two files, two classes, one global name.

M

Each fake is used in one test only. Why does it need a name that the whole project shares?

Mia

A Named Class vs. a Class for One Object

Names are global

Every named class takes a name for the whole program. Small throwaway classes clash.

One object, right here

An anonymous class is declared and instantiated in one expression, where the object is needed.

Closed on purpose

final says "this was not designed to be extended" — and PHP enforces it.

Anonymous Classes and final

Classes for a single use, and classes that stay closed: this chapter covers two opposite ends of class design:

  • Anonymous classes: new class { ... } — a class and its one object in one expression.
  • final classes, methods and constants: stopping extension and overriding where it would break things.
  • Other languages: Java's anonymous and local classes, JavaScript's object literals.

Anonymous classes: new class { ... } declares a class without a name and creates one object of it, right there, in one expression. Inside the braces you write everything a normal class has: properties, methods, a constructor (pass its arguments as new class($a, $b) { ... }), extends and implements. PHP gives the class an internal name starting with class@anonymous, so it never clashes with anything. That's Mia's fix: each test creates new class implements Notifier { ... }, and two tests can have two different fakes without fighting over a name. Since PHP 8.3 an anonymous class can also be readonly.

Mia's bug: two test files, one class name
<?php
// ---- tests/ConfirmTest.php ----
class FakeNotifier { public array $sent = []; }
// ---- tests/RemindTest.php ----
class FakeNotifier { public array $sent = []; }
// Fatal error: Cannot redeclare class FakeNotifier
The fix: an anonymous class in each test
<?php
declare(strict_types=1);
interface Notifier
{
public function send(string $to, string $text): void;
}
function confirmBooking(Notifier $notifier): void
{
$notifier->send("+447700900456", "Confirmed.");
}
$fake = new class implements Notifier { // a class and its object, right here
public array $sent = [];
public function send(string $to, string $text): void
{
$this->sent[] = "$to: $text";
}
};
confirmBooking($fake);
echo count($fake->sent), " sent: ", $fake->sent[0], "\n"; // 1 sent: +447700900456: Confirmed.
var_dump($fake instanceof Notifier); // bool(true)
echo str_starts_with(get_class($fake), "Notifier@anonymous") ? "anonymous" : get_class($fake), "\n";
// anonymous

When to use them: anonymous classes are for objects needed in one place: test doubles, a tiny adapter that makes one object fit an interface, a one-off listener. If the same class is needed twice, or it's more than a few lines, give it a name and a file. And remember that an anonymous class is still a full class — it can be type-checked with instanceof against its interfaces — so code that receives it can't tell the difference.

An anonymous class with constructor arguments
<?php
declare(strict_types=1);
$clock = new class("2026-11-04 09:00") {
public function __construct(private string $now) {}
public function now(): string
{
return $this->now; // a fixed "now" for a test
}
};
echo $clock->now(), "\n"; // 2026-11-04 09:00

final, revisited: Act 11 introduced final. Here's the modern view of it. final class Money can't be extended; final public function confirm() can't be overridden; and since PHP 8.1, final public const RATE = 10; stops a child class from redefining a constant (enum cases and enum classes are always final). A class that can be extended makes a promise to every possible child: its protected members and the way its methods call each other become part of its public design. Many teams therefore make every class final by default and remove it only when inheritance is genuinely planned — composition and interfaces (Act 11) usually do the job better. Value objects and service classes are almost always final.

final constants (PHP 8.1)
<?php
class Pricing
{
final public const HOLIDAY_PERCENT = 10;
}
class CheapPricing extends Pricing
{
public const HOLIDAY_PERCENT = 0; // trying to change the rule in a child
}
// Fatal error: CheapPricing::HOLIDAY_PERCENT cannot override final constant Pricing::HOLIDAY_PERCENT

Anonymous and local classes in Java: Java has anonymous classes too, mostly for one-off implementations of an interface — PHP's work the same way, so there's nothing missing there. Java also has local classes: named classes declared inside a method, visible only there. PHP doesn't support local classes; every named class is declared at the top level of a file (Act 11), and an anonymous class is the way to keep a class local.

Object literals — not in PHP: in JavaScript you can write an object directly, methods included: { name: "Ben", greet() { ... } }. PHP doesn't have object literals with behaviour. The closest are (object) ["name" => "Ben"] or json_decode(), which give a stdClass with data but no methods; as soon as you need behaviour, an anonymous class is PHP's answer. The table below sums up the ways to make a one-off object.

Table — One-off objects
NeedPHPOther languages
Data only, no methods(object) ["name" => "Ben"] → stdClassJavaScript object literal
Behaviour, used oncenew class implements Notifier { ... }Java anonymous class
A named class visible in one methodNot supported: anonymous class or a top-level classJava local class
Methods written inline in an objectNot supported: use an anonymous classJavaScript { greet() { ... } }
stdClass has data, but no behaviour
<?php
$barber = (object) ["name" => "Ben", "chair" => 1]; // closest thing to an object literal
echo get_class($barber), " ", $barber->name, "\n"; // stdClass Ben
$greeter = new class("Ben") { // for behaviour: an anonymous class
public function __construct(public string $name) {}
public function greet(): string { return "Hi, I'm {$this->name}"; }
};
echo $greeter->greet(), "\n"; // Hi, I'm Ben

Key Takeaway

new class { ... } declares a nameless class and creates its one object in a single expression; it can have a constructor, extend a class and implement interfaces, and its internal class@anonymous name never clashes — ideal for test doubles and one-off adapters. final classes, methods and (PHP 8.1) constants close a design on purpose; many teams make classes final by default. PHP has anonymous classes like Java but no local named classes, and no JavaScript-style object literals with methods (stdClass has data only).

Why This Matters

Anonymous classes keep test code and small adapters next to the place they're used, without polluting the project with class names. You'll see them all over PHPUnit tests (Act 21) and in framework code that needs a quick implementation of an interface.

final is the other side of good design: saying clearly which classes are built to be extended and which are not. Final-by-default stops other code from depending on internals you never meant to share — which keeps your classes free to change.

Each test now builds its own anonymous fake, and they run together. Then Mia adds GroupBooking::create() and finds that it returns a plain Booking — the group discount is gone. The factory method in the parent says new self(...). And when she narrows the return type of GroupBooking::find() to ?GroupBooking, she wonders whether PHP will allow it. That's the next chapter: covariance, contravariance and late static binding.