PHP Anonymous Classes: Definition and Instantiation
This article provides a straightforward guide on how to define and instantiate anonymous classes in PHP. Introduced in PHP 7, anonymous classes are ideal for creating simple, one-off objects without the overhead of defining a standard class. You will learn the basic syntax, how to pass arguments to their constructors, and how they can extend other classes or implement interfaces.
What is an Anonymous Class?
An anonymous class is a class that is defined and instantiated at the same time and does not have a designated name. They are highly useful for lightweight, throwaway objects, such as dummy objects for unit testing, simple event listeners, or implementing quick interface structures.
Basic Definition and Instantiation
To define and instantiate an anonymous class, you use the
new class syntax. Here is a basic example:
$logger = new class {
public function log(string $message): void {
echo $message;
}
};
$logger->log("Hello from an anonymous class!");In this example, the class is defined on the fly and its instance is
immediately assigned to the $logger variable.
Passing Arguments to the Constructor
You can pass arguments to an anonymous class’s constructor by placing
parentheses containing the arguments immediately after the
class keyword.
$user = new class("Alice") {
private string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function getName(): string {
return $this->name;
}
};
echo $user->getName(); // Outputs: AliceExtending Classes and Implementing Interfaces
Anonymous classes behave like regular PHP classes and can extend parent classes, implement interfaces, or use traits.
Implementing an Interface
interface Runnable {
public function run(): void;
}
$runner = new class implements Runnable {
public function run(): void {
echo "Running...";
}
};
$runner->run();Extending a Class
class Animal {
public function makeSound(): string {
return "Generic sound";
}
}
$dog = new class extends Animal {
public function makeSound(): string {
return "Bark";
}
};
echo $dog->makeSound(); // Outputs: BarkNested Anonymous Classes
You can also use anonymous classes inside other classes. When nested, an anonymous class does not automatically gain access to the private or protected methods and properties of the outer class. To use outer class properties, you must pass them via the constructor.
class Outer {
private string $prop = 'Outer Property';
public function getInner() {
return new class($this->prop) {
private string $prop;
public function __construct(string $prop) {
$this->prop = $prop;
}
public function getProp(): string {
return $this->prop;
}
};
}
}
$outer = new Outer();
echo $outer->getInner()->getProp(); // Outputs: Outer Property