rfc:allow-closures-to-declare-interfaces-they-implement

PHP RFC: Allow Closures to Declare Interfaces they Implement

Introduction

This RFC proposes the addition of a syntax that allows closures to declare one or more interfaces they implement. This would provide developers with a more explicit and type-safe way to define and interact with closures in PHP. The proposed syntax is as follows:

$f = function ($a) implements FooInterface { ... };

Proposal

The current version of PHP allows closures to be used as a convenient way to define anonymous functions. However, the language does not offer a way to explicitly define the interfaces that a closure implements, which can lead to less clear and less type-safe code. The proposed change would allow closures to declare one or more interfaces they implement, providing a more robust and explicit way to interact with closures.

Since closures implement only one __invoke() method, the interfaces listed when declaring the closure should all declare one single compatible __invoke() method.

The proposed syntax adds an implements keyword followed by one or more interface names to the closure declaration. This addition can be combined with optional return types and the short closure syntax.

Example 1: Closure with a return type and a use statement

$add = function (int $a, int $b) use ($c): int implements AddInterface {
    return $a + $b + $c;
};

Example 2: Closure implementing multiple (and compatible) interfaces

$process = function ($input) use ($config): Result implements ProcessorInterface, ValidatorInterface {
    // ...
};

Example 3: Short closure syntax

$square = fn (int $x): int implements SquarerInterface => $x * $x;

Effect on reflection

Technically, closures are instances of the native Closure class. In order to bind the listed interfaces as proposed by this RFC, closures that implement an interface would have to be instances of a child class of the Closure class.

Conceptually:

$f = function ($a) implements FooInterface { ... };

Should be equivalent to:

$f = new class() extends Closure implements FooInterface {
    public function __invoke($a) {
        ...
    }
};

This RFC does not propose to make this code valid.

This snippet is here to illustrate the possible side-effects of adding an interface to a closure as far as reflection is concerned.

Benefits

Introducing the ability to declare interfaces for closures would provide several benefits:

  • Enhanced type safety: By allowing closures to declare interfaces, type hinting can be used more effectively in function and method signatures that accept closures. This can help prevent runtime errors and improve overall code quality.
  • Improved code readability: By explicitly declaring the interfaces that a closure implements, developers can more easily understand the intended behavior and usage of the closure. This can lead to clearer and more maintainable code.
  • Better IDE support: With the addition of interface declarations for closures, IDEs can provide better code completion, error checking, and refactoring support.
  • Promotes code reusability: By explicitly defining the interfaces that a closure implements, developers can create more modular and reusable code. This can lead to a reduction in code duplication and improved overall design.
  • Easier testing and mocking: Closures implementing interfaces can be more easily replaced with mock objects in unit tests, leading to more robust and maintainable test suites.

Thanks to this feature, it is expected that code authors would shift from type-hinting for Closure to type-hinting for interfaces they could leverage for the purpose of better type safety:

Before:

class Example
{
    /**
     * @param Closure(Input):Result $processor
     */
    function setProcessor(Closure $processor)
    {
        // ...
    }
}
 
(new Example)->setProcessor(fn ($input) => $result);

After:

interface ProcessorInterface
{
    public function __invoke(Input $input): Result;
}
 
class Example
{
    function setProcessor(ProcessorInterface $processor)
    {
        // ...
    }
}
 
(new Example)->setProcessor(fn ($input) implements ProcessorInterface => $result);

Backward Compatibility

The proposed change would be fully backward compatible, as it adds a new feature without affecting existing functionality.

Future Scope

Proposed PHP Version

This RFC targets PHP version 8.3.

Vote

The vote will require a 2/3 majority to be accepted. Voting will start on [Vote start date] and end on [Vote end date].

rfc/allow-closures-to-declare-interfaces-they-implement.txt · Last modified: 2023/04/25 12:15 by nicolasgrekas