There are some advantages:
Before understanding its advantages, it is also necessary to understand the importance of anonymous methods (closures), such as methods that allow callback (i.e., the return of something already expected), the concept is the same for classes.
Such as anonymous functions (closures), anonymous classes are useful when only created and/or used at runtime:
<?php
var_dump((new class {
public function execute() { return 12345; }
})->execute()); // 12345
Another advantage is when we use several classes of the same namespace, now it will be possible to group them instead of repeating the namespace for each class, as detailed below:
Before:
<?php
// PHP 5.6
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
?>
Afterward:
<?php
// PHP 7
use yii\helpers\{ArrayHelper, Html, Url};
?>
Anonymous classes can be imitated (to some extent at least) with relative ease. It also allows us to provide implementations (Implements) of callback for your methods dynamically using closures. Besides doing all the other things a common class already does.
I don’t know if I’m right, but I think there’s something similar in java.
– Wallace Maxters
Yes, Java and C# have this.
– Jéf Bueno
Watch my video on the subject :) https://www.youtube.com/watch?v=9NgLbMo-iQU
– Wallace Maxters