PHP 匿名類
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;
// 使用 new class 創(chuàng)建匿名類
$app->setLogger(new class implements Logger {
public function log(string $msg) {
print($msg);
}
});
$app->getLogger()->log("我的第一條日志");
?>
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 創(chuàng)建匿名類
$app->setLogger(new class implements Logger {
public function log(string $msg) {
print($msg);
}
});
$app->getLogger()->log("我的第一條日志");
?>
以上程序執(zhí)行輸出結(jié)果為:
我的第一條日志
更多建議: