PHP7 匿名类
Posted by 撒得一地 on 2016年3月26日 in PHP笔记
上一篇: PHP7 常量数组
下一篇: PHP7 Closure::call()
下一篇: PHP7 Closure::call()
更详细参见:PHP匿名类
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;
// 使用 new class 创建匿名类
$app->setLogger(new class implements Logger {
public function log(string $msg) {
print($msg);
}
});
$app->getLogger()->log("我的第一条日志");
?>
以上程序执行输出结果为:
我的第一条日志
上一篇: PHP7 常量数组
下一篇: PHP7 Closure::call()
下一篇: PHP7 Closure::call()