lang/php

PHP7 Anonymous Classes - 익명 클래스

C/H 2018. 7. 30. 08:30

익명 클래스

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

$app->getLogger()->log("message"");

// message


반응형