PHP7 anonymous class. What are the advantages?

Asked

Viewed 1,121 times

10

According to the Manual for PHP, from the version PHP 7 it will be possible to 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 gained by the language when implementing the new anonymous class feature?

  • I don’t know if I’m right, but I think there’s something similar in java.

  • 2

    Yes, Java and C# have this.

  • Watch my video on the subject :) https://www.youtube.com/watch?v=9NgLbMo-iQU

2 answers

13


The main advantage is precisely not having to define the class to be able to use it.

At certain times of 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. Better generate an anonymous class at runtime and use it.

2

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.