W3docs

Creating anonymous objects in php

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

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

Example of creating anonymous classes in PHP with new class syntax

<?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.

Alternatively, you can instantiate anonymous classes within closures, for example:

Example of creating anonymous classes in PHP with closures

<?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 examples create and instantiate an anonymous class, which you can use like any other object. Anonymous classes can also accept constructor parameters or extend existing classes, making them useful for testing and dependency injection.

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