O'Reilly logo

PHP 7 Programming Cookbook by Doug Bierer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required