在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
上一篇:
PHP7常量數組
下一篇:
PHP7 Closure::call()