rfc:anonymous_classes

This is an old revision of the document!


PHP RFC: Anonymous Classes

Introduction

For some time PHP has featured anonymous function support in the shape of Closures; this patch introduces the same kind of functionality for objects of an anonymous class.

The ability to create objects of an anonymous class is an established and well used part of Object Orientated programming in other languages (namely C# and Java).

An anonymous class might be used over a named class:

  • when the class does not need to be documented
  • when the class is used only once during execution

An anonymous class is a class without a (programmer declared) name. The functionality of the object is no different from that of an object of a named class. They use the existing class syntax, with the name missing:

var_dump(new class($i) {
    public function __construct($i) {
        $this->i = $i;
    }
});

Use Cases

Following the general advice, the area of code testing appears to present the most significant number of use cases, however, where anonymous classes are a part of a language they do find their way into many areas of development, not just testing. Whether it is technically correct to use an anonymous class depends almost entirely on an individual application, or even object depending on perspective.

Here is one example, which covers converting PSR-7 middleware to Laravel 5-style middleware.

<?php
$conduit->pipe(new class implements MiddlewareInterface {
    public function __invoke($request, $response, $next)
    {
        $laravelRequest = mungePsr7ToLaravelRequest($request);
        $laravelNext    = function ($request) use ($next, $response) {
            return $next(mungeLaravelToPsr7Request($request), $response)
        };
        $laravelMiddleware = new SomeLaravelMiddleware();
        $response = $laravelMiddleware->handle($laravelRequest, $laravelNext);
        return mungeLaravelToPsr2Response($response);
    }
});

Anonymous classes do present the opportunity to create the first kind of nested class in PHP, you might nest for slightly different reasons to creating an anonymous class, so that deserves some discussion;

<?php
class Outside {
    protected $data;
 
    public function __construct($data) {
        $this->data = $data;
    }
 
    public function getArrayAccess() {
        return new class($this->data) extends Outside implements ArrayAccess {
            public function offsetGet($offset) { return $this->data[$offset]; }
            public function offsetSet($offset, $data) { return ($this->data[$offset] = $data); }
            public function offsetUnset($offset) { unset($this->data[$offset]); }
            public function offsetExists($offset) { return isset($this->data[$offset]); }
        };
    }
}
?>

Note: Outer is extended not for access to $this->data - that could just be passed into a constructor; extending Outer allows the nested class implementing ArrayAccess permission to execute protected methods, declared in the Outer class, on the same $this->data, and if by reference, as if they are the Outer class.

In the simple example above Outer::getArrayAccess takes advantage of anonymous classes to declare and create an ArrayAccess interface object for Outer.

By making getArrayAccess private the anonymous class it creates can be said to be a private class.

This increases the possibilities for grouping of your objects functionality, can lead to more readable, some might say more maintainable code.

The alternative to the above is the following:

class Outer implements ArrayAccess {
    public $data;
 
    public function __construct($data) {
        $this->data;
    }
 
    public function offsetGet($offset) { return $this->data[$offset]; }
    public function offsetSet($offset, $data) { return ($this->data[$offset] = $data); }
    public function offsetUnset($offset) { unset($this->data[$offset]); }
    public function offsetExists($offset) { return isset($this->data[$offset]); }
 
}

Pass-by-reference is not used in the examples above, so behaviour with regard to $this->data should be implicit.

How you choose to do it for any specific application, whether getArrayAccess is private or not, whether to pass by reference or not, depends on the application.

Various use cases have been suggested on the mailing list: http://php.markmail.org/message/sxqeqgc3fvs3nlpa?q=anonymous+classes+php

Use Cases from the Community

Below are some excerpts of the discussion on internals mailing list including some use cases that the community see:


The use case is one-time usage of an “implementation”, where you currently probably pass callbacks into a “Callback*”-class like

    $x = new Callback(function() {
        /* do something */
    });
 
    /* vs */
 
    $x = new class extends Callback {
        public function doSometing()
        {
            /* do something */
        }
    });

Imagine you have several abstract methods in one interface/class, which would need several callbacks passed to the constructor. Also '$this' is mapped to the right objects.


It also avoids usage of these classes outside the scope where they are defined...


It is a widely used pattern in object oriented programming ... where you code against interfaces :

$subject->attach(new class implements SplObserver {
  function update(SplSubject $s) {
    printf("Got update from: %s\n" $subject);
  }
});

It would also definitely be very useful for mocking in tests. We could create on-the-fly implementations for interfaces, avoiding using complex mocking API (PHPUnit or others).


There are many use cases where anonymous classes are useful, even in the presence of lambdas. I use them quite often when dealing with graphical interfaces and templates. Here is an example:

abstract class MyFancyHtmlListView extends UI {
  protected function IsHeaderVisible(){ return true; }
  protected function GetListItemMenu(){ return null; }
  protected function OnItemClick( $item ){ }
  protected abstract function RenderListItem( $item );
  public function Render(){
    // echo ...
  }
}

With anonymous classes we could do something like this:

<?= new class extends HTMLView {
  protected function IsHeaderVisible(){
    return false;
  }
  protected function RenderListItem( $item ){
    // echo ...
  }
} ?>

The biggest advantage is that a missing RenderListItem could be statically verified.

It is just a pattern that follows a different way of thinking: Instead of having a list of parameters (including lambdas), we have standard methods that take advantage of all the nice properties of OOP such as abstraction, inheritance and polymorphism.


Playing devil's advocate here, could this feature make the language more expressive?

Take for example an API where you'd typically wrap a method call in try/catch blocks to handle the various “outcomes” e.g. a user login, you'd maybe have a UserDisabled exception, a UserAlreadyLoggedIn exception, a UserPasswordIncorrect exception, etc.

With the addition of this syntactic sugar, the method could instead accept an anonymous class with a onDisabled, onLoggedIn, onPasswordIncorrect methods.

Perhaps it would also have a performance benefit over cascading through catch blocks? Though someone else would have to confirm that.


Overriding a specific method in a class is one handy use. Instead of creating a new class that extends the original class, you can just use an anonymous class and override the methods that you want.

E.G; You can to the following:

use Symfony\Component\Process\Process;
 
$process = new class extends Process {
    public function start() {
        /* ... */
    }
};

instead of the following:

namespace My\Namespace\Process;
 
use Symfony\Component\Process\Process as Base;
 
class Process extends Base {
    public function start() {
        /* ... */
    }
}
 
$process = new \My\Namespace\Process\Process;

One additional use case I can think of is a composition where it is not exposed to the outside of the class. An anonymous class extending a small interface or extending an abstract class with only a few methods seems to be the suitable candidate here IMO. If PHP would support inner classes I would probably prefer a private inner class when the anonymous class starts to hold to much logic.

Backward Incompatible Changes

New syntax that will fail to parse in previous versions, so no BC breaks.

Proposed PHP Version(s)

7.0

SAPIs Impacted

All

Impact to Existing Extensions

No impact on existing libraries

Open Issues

The question of whether or not to disable serialization for anonymous objects.

Future Scope

The changes made by this patch mean named nested classes are easier to implement (by a tiny bit).

Proposed Voting Choices

Straight forward, we should have this, we should not have this.

Syntax and Examples

new class (arguments) {definition}

Note: in a previous version of this RFC, the arguments were after the definition, this has been changed to reflect the feedback during the last discussion.

<?php
/* implementing an anonymous console object from your framework maybe */
(new class extends ConsoleProgram {
    public function main() {
       /* ... */
    }
})->bootstrap();
 
/* return an anonymous implementation of a Page for your MVC framework */
return new class($controller) implements Page {
    public function __construct($controller) {
        /* ... */
    }
    /* ... */
};
 
/* vs */
class MyPage implements Page {
    public function __construct($controller) {
        /* ... */
    }
    /* ... */
}
return new MyPage($controller);
 
/* return an anonymous extension of the DirectoryIterator class */
return new class($path) extends DirectoryIterator {
   /* ... */
};
 
/* vs */
class MyDirectoryIterator {
    /* .. */
}
return new MyDirectoryIterator($path);
 
/* return an anon class from within another class (introduces the first kind of nested class in PHP) */
class MyObject extends MyStuff {
    public function getInterface() {
        return new class implements MyInterface {
            /* ... */
        };
    }
}
 
 
/* return a private object implementing an interface */
class MyObject extends MyStuff {
    /* suitable ctor */
 
    private function getInterface() {
        return new class(/* suitable ctor args */) extends MyObject implements MyInterface {
            /* ... */
        };
    }
}
 
?>

Note: the ability to declare and use a constructor in an anonymous class is necessary where control over construction must be exercised.

Code Paths

Code such as:

while ($i++<10) {
    class myNamedClass {
        /* ... */
    }
}

will fail to execute, however code such as:

while ($i++<10) {
  new class {};
}

will work as expected: the definition will be re-used, creating a new object.

Internal Class Naming

The internal name of an anonymous class is generated based on the scope which created it, such that:

function my_factory_function(){
    return new class{};
}

get_class(my_factory_function()) would return my_factory_function$$1

And in the following example:

class Other {
    public function getMine() {
        return new class{};
    }
}

get_class1)->getMine()) would return Other$$1

Finally:

var_dump(get_class(new class{}));

in the global scope would return Class$$1 on the first execution.

Comparisons

Multiple anonymous classes created in the same position (say, a loop) can be compared with `==`, but those created elsewhere will not match as they will have a different name.

<php> <?php

$identicalAnonClasses = [];

for ($i = 0; $i < 2; $i++) {

  $identicalAnonClasses[$i] = new class(99) {
      public $i;
      public function __construct($i) {
          $this->i = $i;
      }
  };

}

var_dump($identicalAnonClasses[0] == $identicalAnonClasses[1]); true $identicalAnonClasses[2] = new class(99) { public $i; public function __construct($i) { $this->i = $i; } }; var_dump($identicalAnonClasses[0] == $identicalAnonClasses[2]); false </code>

Both classes where identical in every way, other than their generated name.

Inheritance

Some have queried how inheritance might work and suggested the utilization of the “use” statement.

This doesn't appear to be necessary; anonymous classes have constructors and support inheritance like any other class, as the examples show.

It seems to me that use($my, $arguments) is not actually different from passing those arguments to a constructor, they are for all intents and purposes the same thing.

Other options have been toyed with, such as a super:: keyword, but dropped ...

Bottom line: should you need the functionality of an anonymous class to be tightly coupled to another object, then it's reasonable that you should utilize normal inheritance and passing by reference in order to achieve that coupling.

Reflection

The only change to reflection is to add ReflectionClass::isAnonymous().

Implementation

References

Changelog

* v0.3: ReflectionClass::isAnonymous() and simple example * v0.2: Brought back for discussion * v0.1: Initial drafts

1)
new Other(
rfc/anonymous_classes.1424902859.txt.gz · Last modified: 2017/09/22 13:28 (external edit)