
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Anonymous classes in PHP 7?
Anonymous classes in PHP 7 can be defined using the new class. It can be used instead of full class definition as well. Why use anonymous classes?
- Mocking tests is easy.
- Dynamic implementations for interfaces can be created easily, thereby avoiding the usage of complex mocking APIs.
They can be placed in the scope where they had been defined.
The usage of autoloader for simple implementations can be avoided.
Example
Below is a code sample −
<?php interface a_logger { public function log(string $msg); } class App { private $logger; public function getLogger(): a_logger { return $this->logger; } public function setLogger(a_logger $logger) { $this->logger = $logger; } } $app = new App; $app->setLogger(new class implements a_logger { public function log(string $msg) { print($msg); } }); $app->getLogger()->log("This has created an anonymous class"); ?>
Output
This will produce the following output −
This has created an anonymous class
- Related Articles
- PHP Anonymous classes
- Anonymous classes in C++
- What are anonymous inner classes in Java?
- PHP Anonymous functions
- How are anonymous (inner) classes used in Java?
- Creating anonymous objects in PHP
- How many types of anonymous inner classes are defined in Java?
- PHP Autoloading Classes
- PHP Accessing Global classes
- Access variables from parent scope in anonymous PHP function
- How can we use a diamond operator with anonymous classes in Java 9?
- Preg_replace_callback_array() in PHP 7
- Migrating PHP 5.x to PHP 7 on CentOS 7
- Generator delegation in PHP 7
- Type Hinting in PHP 7

Advertisements