首页 > 编程教程 > PHP7 教程
2016
09-20

PHP7匿名类

在php7中,匿名类现在可以使用 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

关注编程技巧 回复19领350本编程书籍

编程技巧