rfc:anonymous_classes

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;

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.

Inheritance/Traits

Extending classes works just as you'd expect.

<?php
 
class Foo {}
 
$child = new class extends Foo {};
 
var_dump($child instanceof Foo); // true

Traits work identically as in named class definitions too.

<?php
 
trait Foo {
    public function someMethod() {
      return "bar";
    }
}
 
$anonClass = new class {
    use Foo;
};
 
var_dump($anonClass->someMethod()); // string(3) "bar"

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
 
$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

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

Reflection

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

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.

Implementation

References

Changelog

  • v0.5: Added traits example and tests
  • v0.4: Comparisons example
  • v0.3: ReflectionClass::isAnonymous() and simple example
  • v0.2: Brought back for discussion
  • v0.1: Initial drafts
1) new Other(
rfc/anonymous_classes.txt · Last modified: 2015/03/04 20:17 by philstu