PHP Anonymous Classes

PHP 7 New Features

PHP 7 supports usingnew classto instantiate an anonymous class, which can be used to replace some complete class definitions that are "use-and-discard".

Example

Example

<?php
interface Logger {
   public function
log(string $msg);
}

class
Application {
   private
$logger;

   public function
getLogger(): Logger {
      return
$this->logger;
   }

   public function
setLogger(Logger $logger) {
      
$this->logger = $logger;
   }  
}

$app = new Application;
// Use new class to create an anonymous class
$app->setLogger(new class implements Logger {
   public function
log(string $msg) {
      print(
$msg);
   }
});

$app->getLogger()->log("My first log entry");
?>

The output of the above program is:

My first log entry

PHP 7 New Features

Other Extensions