PHP 7 introduced a new feature, anonymous classes. Much like anonymous functions, anonymous classes can be defined as part of an expression, creating a class that has no name. Anonymous classes are used in situations where you need to create an object on the fly, which is used and then discarded.
An alternative to
stdClass
is to define an anonymous class.In the definition, you can define any properties and methods (including magic methods). In this example, we define an anonymous class with two properties and a magic method,
__construct()
:$a = new class (123.45, 'TEST') { public $total = 0; public $test = ''; public function __construct($total, $test) { $this->total = $total; $this->test = $test; } };
An anonymous class can extend any class.
In this example, an anonymous class extends
FilterIterator
, and overrides both the__construct()
andaccept()
methods. As an argument, it acceptsArrayIterator
$b
, which represents...