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 −

 Live Demo

<?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

Updated on: 06-Apr-2020

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements