开发学院

您的位置:首页>教程>正文

教程正文

PHP 7 匿名类

PHP 7 匿名类

  现在可以使用new class定义匿名类,可以使用匿名类来代替完整的类定义。

例子

<?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;
   $app->setLogger(new class implements Logger {
      public function log(string $msg) {
         print($msg);
      }
   });

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

  上述代码输出内容如下:

My first Log Message