QA
Intermediate LevelPHP 8+

How do PHP 7+ Anonymous Classes work and why are they useful in unit testing?

❓ Interview Prompt: Explain anonymous class instantiation (new class extends/implements), passing constructor arguments, and building lightweight mocks.

PHP 7 introduced Anonymous Classes ('new class implements Interface {}'), allowing on-the-fly instantiation of unnamed objects.

Use Cases:

1
Lightweight Unit Test Mocks: Quickly implement interface stubs in tests without creating dedicated '.php' class files.
2
One-Off Event Handlers: Pass single-use callback implementations to framework event dispatchers.

Code Implementation Example

php
<?php
interface LoggerInterface {
    public function log(string $msg): void;
}

// Instantiate an Anonymous Class implementing LoggerInterface on the fly!
$mockLogger = new class implements LoggerInterface {
    public array $logs = [];
    public function log(string $msg): void {
        $this->logs[] = $msg;
    }
};

$service = new OrderService($mockLogger);
$service->process();
var_dump($mockLogger->logs); // Inspect captured log calls in unit test!
💡Creating an anonymous class implementing LoggerInterface for unit testing mocks.
🎯 Interview Key Takeaway

Anonymous classes (new class implements Interface) create inline, one-off objects ideal for lightweight testing mocks.

#Anonymous Classes#OOP#Testing#Intermediate
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?