Easy Tutorial
❮ Func Simplexml Load String Func Xml Error String ❯

PHP Anonymous Classes

PHP 7 New Features

PHP 7 supports instantiating an anonymous class via new class, which can be used to replace some "disposable" full class definitions.

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;
// Using 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");
?>

The output of the above program is:

My first log

PHP 7 New Features

❮ Func Simplexml Load String Func Xml Error String ❯