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.
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;
}
};In this example, an anonymous class extends FilterIterator, and overrides both the __construct() and accept() methods. As an argument, it accepts ArrayIterator $b, which represents an array of 10 to 100 in increments of 10. The second argument serves as a limit on the output:
$b = new ArrayIterator(range(10,100,10));
$f = new class ($b, 50) extends FilterIterator {
public $limit = 0;
public function __construct($iterator, $limit)
{
$this->limit = $limit;
parent::__construct($iterator);
}
public function accept()
{
return ($this->current() <= $this->limit);
}
};In this example, an anonymous class is used to generate an HTML color code chart. The class implements the built-in PHP Countable interface. A count() method is defined, which is called when this class is used with a method or function that requires Countable:
define('MAX_COLORS', 256 ** 3);
$d = new class () implements Countable {
public $current = 0;
public $maxRows = 16;
public $maxCols = 64;
public function cycle()
{
$row = '';
$max = $this->maxRows * $this->maxCols;
for ($x = 0; $x < $this->maxRows; $x++) {
$row .= '<tr>';
for ($y = 0; $y < $this->maxCols; $y++) {
$row .= sprintf(
'<td style="background-color: #%06X;"',
$this->current);
$row .= sprintf(
'title="#%06X"> </td>',
$this->current);
$this->current++;
$this->current = ($this->current >MAX_COLORS) ? 0
: $this->current;
}
$row .= '</tr>';
}
return $row;
}
public function count()
{
return MAX_COLORS;
}
};Test, we define an anonymous class instead:$a = new class() {
use IdTrait, NameTrait {
NameTrait::setKeyinsteadofIdTrait;
IdTrait::setKey as setKeyDate;
}
};In an anonymous class you can define any properties or methods. Using the preceding example, you could define an anonymous class that accepts constructor arguments, and where you can access properties. Place the code described in step 2 into a test script chap_04_oop_anonymous_class.php. Add these echo statements:
echo "\nAnonymous Class\n"; echo $a->total .PHP_EOL; echo $a->test . PHP_EOL;
Here is the output from the anonymous class:

In order to use FilterIterator you must override the accept() method. In this method, you define criteria for which elements of the iteration are to be included as output. Go ahead now and add the code shown in step 4 to the test script. You can then add these echo statements to test the anonymous class:
echo "\nAnonymous Class Extends FilterIterator\n"; foreach ($f as $item) echo $item . ''; echo PHP_EOL;
In this example, a limit of 50 is established. The original ArrayIterator contains an array of values, 10 to 100, in increments of 10, as seen in the following output:

To have a look at an anonymous class that implements an interface, consider the example shown in steps 5 and 6. Place this code in a file, chap_04_oop_anonymous_class_interfaces.php.
Next, add code that lets you paginate through the HTML color chart:
$d->current = $_GET['current'] ?? 0;
$d->current = hexdec($d->current);
$factor = ($d->maxRows * $d->maxCols);
$next = $d->current + $factor;
$prev = $d->current - $factor;
$next = ($next <MAX_COLORS) ? $next : MAX_COLORS - $factor;
$prev = ($prev>= 0) ? $prev : 0;
$next = sprintf('%06X', $next);
$prev = sprintf('%06X', $prev);
?>Finally, go ahead and present the HTML color chart as a web page:
<h1>Total Possible Color Combinations: <?= count($d); ?></h1> <hr> <table> <?= $d->cycle(); ?> </table> <a href="?current=<?= $prev ?>"><<PREV</a> <a href="?current=<?= $next ?>">NEXT >></a>
Notice that you can take advantage of the Countable interface by passing the instance of the anonymous class into the count() function (shown between <H1> tags). Here is the output shown in a browser window:

Lastly, to illustrate the use of traits in anonymous classes, copy the chap_04_oop_trait_multiple.php file mentioned in the previous recipe to a new file, chap_04_oop_trait_anonymous_class.php. Remove the definition of the Test class, and replace it with an anonymous class:
$a = new class() {
use IdTrait, NameTrait {
NameTrait::setKeyinsteadofIdTrait;
IdTrait::setKey as setKeyDate;
}
};Remove this line:
$a = new Test();
When you run the code, you will see exactly the same output as shown in the preceding screenshot, except that the class reference will be anonymous:
