PHP7 anonymous class. What are the advantages?

10

According to the PHP Manual , from the PHP 7 version you can define anonymous classes.

Example:

class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}

// Instanciamos a classe anonima aqui:
var_dump(new class(10) extends SomeClass implements SomeInterface {
    private $num;

    public function __construct($num)
    {
        $this->num = $num;
    }

    use SomeTrait;
});

What would be the advantages of language when implementing the new feature of the anonymous class?

    
asked by anonymous 10.09.2015 / 18:29

2 answers

13

The main advantage is that you do not need to define the class in order to use it.

At certain times in the application, you need to use a class to, for example, represent a data structure or inherit some class that already exists and have extra methods. If the class is too little used in the application (for example, once in the whole system), it is not worth declaring it. Best to generate an anonymous class at runtime and use it.

    
10.09.2015 / 18:59
2

There are some advantages:

Before understanding its vantages, it is also necessary to understand the importance of anonymous methods (closures), such as the methods that allow callback (ie, the return of something already expected), the concept is the same for classes.

Such as closures, anonymous classes are useful when just 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 you can group them instead of repeating the namespace for each class, as follows:

Before:

<?php
// PHP 5.6
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
?>

After:

<?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 callback implementations for your methods dynamically using closures . Besides doing all the other things an ordinary class already does.

    
16.09.2015 / 14:55