PHP 7: Maintaining and Upgrading Legacy Apps · PHP 7 Language Essentials

Anonymous Classes, Generators and Closures in PHP 7

Recognize and modernize idioms common in PHP 7 code.

PHP 7 codebases often use anonymous classes (new class implements Logger {}) for quick test doubles, generators with yield from and return values (7.0), and closures with Closure::fromCallable() (7.1) or $closure->call($obj) (7.0). Recognizing these lets you maintain them and later replace some with PHP 8 equivalents like first-class callable syntax.

<?php
$logger = new class implements LoggerInterface {
    use Psr\Log\LoggerTrait;
    public array $records = [];
    public function log($level, $message, array $context = []): void
    {
        $this->records[] = [$level, $message];
    }
};

function numbers(): Generator
{
    yield 1;
    yield from [2, 3];
    return 3;                      // retrieve with ->getReturn()
}

$validator = Closure::fromCallable([$this, 'validate']);   // PHP 8.1: $this->validate(...)

Common pitfalls

  • Using anonymous classes for production services, making them hard to reference and test.
  • Calling getReturn() before a generator has finished.
  • Binding closures to objects (bindTo) in ways that hide dependencies.

Key points

  • Anonymous classes suit quick test doubles
  • Generators support yield from and return values
  • Closure::fromCallable → first-class callables in PHP 8.1

Further reading: PHP manual: anonymous classes

Practice questions

When are anonymous classes useful?

Answer

For small one-off implementations of an interface, especially test doubles or adapters, where a named class would be overkill.

How does Closure::fromCallable() relate to PHP 8.1?

Answer

It creates a Closure from any callable; PHP 8.1's first-class callable syntax ($obj->method(...)) does the same more concisely and is easier for tools to analyze.

Open in the app to mark lessons complete, take notes and track your progress.