Anonymous Classes
PHP 7.0 added anonymous classes — inline, disposable class definitions. They're perfect for one-off implementations, testing, and anywhere you'd create a class that's only used once.
// Perfect for tests — no need to create a file for a stub
$logger = new class implements LoggerInterface {
public array $logs = [];
public function log($level, $message, array $context = []): void {
$this->logs[] = compact('level', 'message', 'context');
}
// ... other PSR-3 methods
};
$service = new MyService($logger);
$service->doWork();
$this->assertCount(3, $logger->logs);
// Inline adapters
function createCacheAdapter(array &$store): CacheInterface {
return new class($store) implements CacheInterface {
public function __construct(private array &$store) {}
public function get(string $key, mixed $default = null): mixed {
return $this->store[$key] ?? $default;
}
public function set(string $key, mixed $value, int $ttl = 0): bool {
$this->store[$key] = $value;
return true;
}
};
}
// They support everything normal classes do:
// constructors, interfaces, traits, inheritance, properties
$event = new class('click', ['x' => 100]) extends Event implements Serializable {
use HasMetadata;
public function __construct(public string $type, public array $data) {
parent::__construct();
}
};
Anonymous classes reduce file proliferation. Instead of creating StubLogger.php for a single test, you define it inline where it's used. The class exists only in the scope where it's created — no namespace pollution, no autoloading overhead.
Significance: Pragmatism
Not every class deserves a file. Anonymous classes let you create focused, single-use implementations without the overhead of naming, filing, and autoloading a class you'll never reference again. They're especially powerful in tests, where stub proliferation is a real maintenance burden.