Anonymous (class)es
Anonymous classes
Support for anonymous classes was added in PHP 7. Anonymous classes are useful when simple, one-off objects need to be created.
<?php // Pre PHP 7 code class Logger { public function log($msg) { echo $msg; } } $util->setLogger(new Logger()); // PHP 7+ code $util->setLogger(new class { public function log($msg) { echo $msg; } });
They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:
<?php class SomeClass {} interface SomeInterface {} trait SomeTrait {} var_dump(new class(10) extends SomeClass implements SomeInterface { private $num;