Skip to main content
An anonymous class in PHP is an unnamed, single-use object blueprint instantiated at the exact moment of its declaration. Introduced in PHP 7.0, it provides a mechanism to create disposable objects that encapsulate state and behavior without polluting the global namespace with formal class definitions.

Basic Syntax

The declaration and instantiation occur simultaneously using the new class construct.

Constructor Arguments

Arguments can be passed to the anonymous class constructor by placing parentheses immediately after the class keyword.

Inheritance, Interfaces, and Traits

Anonymous classes support the full PHP object-oriented paradigm. They can extend base classes, implement multiple interfaces, and consume traits exactly like named classes.

Internal Engine Naming

While conceptually “anonymous,” the PHP engine assigns a unique internal identifier to the class at runtime. This identifier is based on the memory address or the file path and line number where the class was declared.
Because the engine caches the class definition based on its declaration point, multiple instantiations from the exact same declaration line (e.g., inside a loop) will share the same internal class type, meaning $obj1 instanceof $obj2 will evaluate to true.

Scope and Context

An anonymous class does not inherit the variable scope of the context in which it is defined. When declared inside a method of an outer class, the anonymous class cannot automatically access the outer class’s private or protected members. To grant access to the outer scope, you must explicitly pass the required data via the constructor, or the anonymous class must explicitly extend the outer class.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More