Creating anonymous objects in php

In PHP, anonymous objects can be created using the new class syntax. For example:

<?php
$obj = new class {
  public $property = 'value';

  public function method()
  {
    return 'Hello, world!';
  }
};

echo $obj->property . "\n";
echo $obj->method() . "\n";

This creates an anonymous class with a public property $property and a public method method(). The class is then instantiated and assigned to the variable $obj.

Watch a course Learn object oriented PHP

Alternatively, Anonymous classes can also be created using closures, for example:

<?php
$factory = function () {
  return new class {
    public $property = 'value';

    public function method()
    {
      return 'Hello, world!';
    }
  };
};

$obj = $factory();

echo $obj->property . "\n";
echo $obj->method() . "\n";

Both of these examples create an anonymous class and instantiate it, you can use the object like any other object.

Please note that Anonymous classes are available only in PHP 7.0 and later versions.