Implementing anonymous classes

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.

How to do it...

  1. 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; } ...

Get PHP 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.