
PHP anonymous classes are a powerful feature that allows you to create classes on the fly without declaring them beforehand.
They can be defined using the new class keyword followed by a class definition enclosed in parentheses. For example, $obj = new class { }; creates an anonymous class.
This can be useful for creating one-off classes or for testing purposes.
In the following example, an anonymous class is used to implement the Counter interface: $counter = new class implements Counter { public function count() { return 1; } };.
Take a look at this: Akismet
Creating a Class
You can create a basic anonymous class in PHP by following a specific syntax.
An anonymous class is similar to a normal named class, in the sense that it can contain properties and methods.
Its functionality is no different from that of an object of a named class.
Anonymous classes are useful when simple, one-off objects need to be created.
Class Dependencies
Class dependencies are a crucial aspect of PHP anonymous classes. You can send dependencies to an anonymous class via its constructor, making it suitable for dynamic, one-time use cases.
This approach is particularly useful for small, temporary tasks, such as injecting a logger or another service directly into an anonymous class.
Internal Naming

Internal naming of anonymous classes is a unique aspect of PHP. It assigns an internal name to each anonymous class, which can be obtained using the get_class() function.
This internal name is generated with a unique reference based on the class's address. The word "class" is used by default, but if the anonymous class extends a named class, it will use that class's name instead.
For example, if we call my_factory_function() multiple times, get_class() would return the same internal name, even if the class is recreated. This internal name is not just a static value, but a dynamic reference to the class's address.
We can compare anonymous classes created in the same position using the == operator, but those created elsewhere will not match due to their different internal names. This is because the internal name is generated based on the class's address, not its definition.
Worth a look: Php Store Class Name in Variable
Class Dependencies
Class dependencies can be sent to an anonymous class via its constructor, making it suitable for dynamic, one-time use cases.

This approach is particularly useful for injecting a logger or another service directly into an anonymous class, which is helpful for small, temporary tasks.
Dependencies can be injected into an anonymous class, making it a great solution for one-time use cases.
This method is especially useful for tasks that require a specific service or logger, but only for a short period of time.
You can inject a logger or another service into an anonymous class, which is beneficial for small, temporary tasks.
Syntax and Examples
In PHP, an anonymous class is defined using the `new class` syntax. The syntax is straightforward: `new class (arguments) { definition }`.
Note that the arguments are now placed before the definition, a change made in response to community feedback. This is a deliberate design choice to improve the usability of anonymous classes.
You can use an anonymous class to exercise control over construction, which is necessary in certain situations. By declaring and using a constructor in an anonymous class, you can ensure that your objects are created with the desired properties and behavior.
Example: Internal Name

PHP assigns an internal name to an anonymous class, which can be obtained using the get_class() function. This internal name is unique and based on the class's address.
The internal name is generated with a unique reference based on the class's address. The word "class" is used by default, but if the anonymous class extends a named class, it will use that name instead.
For example, get_class(my_factory_function()) returns "class@0x7fa77f271bd0", even if called multiple times. This is because it's the same definition, and the address remains the same.
Multiple anonymous classes created in the same position can be compared using ==, but those created elsewhere will not match. This is because they will have a different name, even if they're identical in every way.
By making getArrayAccess private, the anonymous class it creates can be said to be a private class. This is a useful technique to keep in mind when working with anonymous classes.
Related reading: Php This Class Name
Syntax and Examples

In a class declaration, the arguments are now placed before the definition, a change made after feedback from the discussion.
The syntax for declaring an anonymous class is new class (arguments) {definition}. This syntax is a result of a revision to the previous version of the RFC.
The ability to declare and use a constructor in an anonymous class is necessary for exercising control over construction.
In the revised syntax, the arguments are placed before the definition, a change from the previous version.
Readers also liked: Change Css Class Javascript
Using Methods
Using Methods in PHP Anonymous Classes is a powerful feature that allows you to create objects without declaring a class.
You can define methods in an anonymous class, such as the addition() and division() methods in the code example.
These methods can be called with the object, as shown in the example where the addition() and division() methods are called with the $obj object.
You can store the anonymous class in a variable, such as $obj, to use its methods later in your code.
By using methods in PHP anonymous classes, you can create more complex and dynamic objects that can perform various tasks.
Use Cases
Anonymous classes in PHP are incredibly useful, and their use cases are numerous. They can be used for mocking tests, making it easy to create on-the-fly implementations for interfaces without relying on complex mocking APIs.
One of the key benefits of anonymous classes is that they keep their usage outside the scope where they are defined. This makes them ideal for situations where you need to create a class that is only used once.
Here are a few quick points to keep in mind:
- Mocking tests becomes easy as pie. Create on-the-fly implementations for interfaces, avoiding using complex mocking APIs.
- Keep usage of these classes outside the scope they are defined in
- Avoid hitting the autoloader for trivial implementations
For example, the Pusher PHP library uses anonymous classes to tweak existing classes without creating a new file or placing the class definition at the top of the file. This is especially useful for big complex actions or anything that needs to be reused as a named class.
Readers also liked: Anonymous File Hosting
Anonymous classes can also be used to implement a very light interface to create a simple dependency, such as converting PSR-7 middleware to Laravel 5-style middleware. This can lead to more readable and maintainable code by allowing you to group related functionality together.
The use of anonymous classes depends on the application, so it's up to you to decide how to implement them. But with their flexibility and convenience, it's no wonder they're a popular choice among developers.
Implementing an Interface
Implementing an interface is a straightforward process with anonymous classes. An anonymous class can implement one or multiple interfaces, making it a convenient option for certain use cases.
You can define an interface with a specific method, like the log() method in the Logger interface. Then, an anonymous class can implement this interface, giving you an instance that conforms to the interface.
The instance of the anonymous class can be used as if it were a normal class, but with one key difference: you can't use a type hint for its instance because it doesn't have a declared name. However, you can still use the type hint via the interface it implements.
This flexibility makes anonymous classes particularly useful for mocking tests, allowing you to easily create test doubles that conform to a specific interface.
On a similar theme: How to Use Classes in Webflow
Inheriting a Class
Inheriting a class is a fundamental concept in PHP, and it's quite straightforward.
A class can inherit from one named class, just like a regular class.
To pass an argument to the constructor, we place it in parentheses that follow the class keyword.
You can extend the SimpleLogger class to create a new class.
The constructor of the anonymous class calls the constructor of the SimpleLogger class.
This allows you to build upon existing code and create new classes with added functionality.
We call the constructor of the SimpleLogger class in the constructor of the anonymous class.
Finally, you can call the log() method of the $logger object.
Take a look at this: How to Call a Class in Css
When To Use
When to use anonymous classes in PHP, it's essential to consider the following scenarios:
Anonymous classes are helpful in some cases, such as when you need to create a class on the fly without defining a new class. They are especially useful when you want to create a class that is only used once.
Intriguing read: Css Animation When Class Is Removed
Use anonymous classes to create on-the-fly implementations for interfaces, making mocking tests easy as pie.
To make the most of anonymous classes, keep their usage outside the scope where they are defined. This means avoiding using them within the same scope they are defined in.
Anonymous classes can be used to tweak existing classes that only need a single change, making it easy to avoid creating a new file or placing the class definition at the top of the file.
Here are some specific use cases for anonymous classes:
- Mocking tests become easy as pie
- Keep usage of these classes outside the scope they are defined in
- Avoid hitting the autoloader for trivial implementations
In some cases, anonymous classes are a better choice than creating a new class or using a callback. For example, when you need to implement a very light interface to create a simple dependency, anonymous classes can be a great solution.
Anonymous classes can also be used to override a specific method in a class, instead of creating a new class that extends the original class.
Frequently Asked Questions
What version of PHP is anonymous class?
Anonymous classes were introduced in PHP version 7.0, allowing for classes without a declared name. This feature enables one-time use of a class definition.
Featured Images: pexels.com


