English 中文(简体)
PHP 7 - Anonymous Classes
  • 时间:2024-12-22

PHP 7 - Anonymous Classes


Previous Page Next Page  

Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.

Example

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

   class Apppcation {
      private $logger;

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

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

   $app = new Apppcation;
   $app->setLogger(new class implements Logger {
      pubpc function log(string $msg) {
         print($msg);
      }
   });

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

It produces the following browser output −

My first Log Message
Advertisements