Latest web development tutorials

PHP anonymous class

PHP 7 New Features PHP 7 New Features

PHP 7 support vianew class to instantiate an anonymous class, which can be used to replace some of the "burn after use" a complete class definition.

Examples

Examples

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

$ app -> getLogger () - > log ( " my first log");
?>

The above program execution output is:

我的第一条日志

PHP 7 New Features PHP 7 New Features