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.


Below is a code sample −

 Live Demo

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) {
$app->getLogger()->log("This has created an anonymous class");


This will produce the following output −

This has created an anonymous class