

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- PHP Anonymous classes
- Anonymous classes in C++
- PHP Anonymous functions
- What are anonymous inner classes in Java?
- How are anonymous (inner) classes used in Java?
- Preg_replace_callback_array() in PHP 7
- Creating anonymous objects in PHP
- Migrating PHP 5.x to PHP 7 on CentOS 7
- Generator delegation in PHP 7
- Type Hinting in PHP 7
- Constant arrays in PHP 7
- PHP Autoloading Classes
- Group Use declarations in PHP 7
- Generator Return Expressions in PHP 7
- Exceptions and Error in PHP 7
Advertisements