12

As I looked for the new PHP7-features I stumbled upon anonymous classes.

I didn't understand when they should become useful, and looked for an example.

I read this article, but I don't see the benefits of this feature.

In the last section before the conclusion they wrote the following about the advantages:

One advantage is that we no longer need the named extension. Normally the named extension would be hidden away in some included file, if you ever needed to see how it is defined you have to start searching for it. With anonymous classes the definition is in the same place the object is created.

On the other hand, I see a big disadvantage because you can use this anonymous class only at the place it is defined.

Can someone please explain when this feature is useful?

Especially if it can help when building custom systems or extending a CMS like WordPress (preferably in German, although English is also welcome).

Kache
  • 15,647
  • 12
  • 51
  • 79
  • 5
    A language feature is useful when you need it. Don't try to use it just because it is new and shiny, if you couldn't find a use case for it. – axiac Mar 01 '19 at 09:06
  • I think it'd be useful if you're using it as a function argument that requires a certain [interface](http://php.net/manual/en/language.oop5.interfaces.php) which you can easily implement in a few line of code. – Koala Yeung Mar 01 '19 at 09:12
  • 6
    Good answer to a similar question https://stackoverflow.com/questions/31433462/anonymous-classes-in-php-7 – Tali Luvhengo Mar 01 '19 at 09:13
  • 1
    @axiac That is the point I want to know in which use cases this feature will come in handy. I couldn't think of any but maybe I'm not as smart as the people who use frameworks even for a simple task. Personally I didn't use any php frameworks because I haven't found a use cases for it and also many of them (e.g. symfony) require additional packages that have to be installed on the server. So portability couldn't be guaranted. – Alexander Behling Mar 01 '19 at 09:32
  • I would put it the other way around: you'll know when you'll need it. – axiac Mar 01 '19 at 10:03

2 Answers2

3

Anonymous classes could be useful in writing implementation classes for listener interfaces, so you don't need to create a file or a generic class just to implement once.

One of the most elegant things about anonymous classes is that they allow you to define a one-shot class exactly where it is needed. In addition, anonymous classes have a succinct syntax that reduces clutter in your code. Java in a nutshell

So, you can have an anonymous implementation of an interface or even extend a class, with additional properties or overwritten methods.

Example:

return new class(10) extends SomeClass implements SomeInterface {
    private $num;

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

Another situation:

Provide a simple implementation of an adapter class. An adapter class is one that defines code that is invoked by some other object. Take, for example, the list() method on a class called File. This method lists the files in a directory. Before it returns the list, though, it passes the name of each file to a FilenameFilter object you must supply. This FilenameFilter object accepts or rejects each file. When you implement the FilenameFilter interface, you are defining an adapter class for use with the $file->list() method. Since the body of such a class is typically quite short, it is easy to define an adapter class as an anonymous class.

$file = new File("/src");

// Now call the list() method with a single FilenameFilter argument
// Define and instantiate an anonymous implementation of FilenameFilter
// as part of the method invocation expression. 
$filelist = $file->list(new class extends FilenameFilterClass {
  public function accept(File $f, string $otherInfo) { 
    return pathinfo($f, PATHINFO_EXTENSION) === ".php"; 
  }
});

Some nice basic understanding and use about anonymous classes could be found on Java (I know its not PHP, but it helps on understanding) examples at https://www.geeksforgeeks.org/anonymous-inner-class-java/

Marcel Kohls
  • 1,650
  • 16
  • 24
  • Thanks for the interesting link. I has helped me a lot because I have also coded in java long time ago (version 1.4.*) Actually I could not think of any use in the projects I'm working on. But maybe in future this feature will come in handy. – Alexander Behling Mar 01 '19 at 09:44
  • You're welcome. In fact, I also didn't use it commonly on PHP, but on javascript is more common for me. – Marcel Kohls Mar 01 '19 at 09:47
  • Glad to hear I'm not alone :-) Anonymous classes in javascript?! Could you give me an example? I only use lambda functions because I actually use the jQuery-Framework. In the past I also had to use the "pain in the ass"-framework scriptaculous. Even by thinking about coding an event handler in this framework I got a headache. – Alexander Behling Mar 01 '19 at 09:55
  • That's the same idea, but I can see more use cases on js. For example, instantiate a class based on an ajax response and setting specific properties/methods: var Animal = class { constructor(name) { this.name = name; } }; – Marcel Kohls Mar 01 '19 at 09:59
  • I see, therefore you haven't to load a file that contains the class definition. So this should be faster. – Alexander Behling Mar 01 '19 at 10:20
0

I should use a anonymous class only if this class is not used anywhere else and if these class isn't changed since the first coding.
So for example a database class could maybe a candidate for using a anonymous class because it should be use only once and could be included in any other php file. In most cases the data for accessing the database is in the config file. Therefore this file should be loaded for every php file that is using the database when you want to avoid the hard coding of the database params (which is a bad idea). If you coded these class as an anonymous class in the config file you have eliminated one include whithout losing the maintainance.