rfc:typesafe-callable

This is an old revision of the document!


PHP RFC: Typesafe callable

Introduction

Currently, when you typehint against “callable” in your method signatures, you can never be certain whether it accepts the parameters you are giving it or if the return type is what you'd expect. You can of course validate the return type, and catch exceptions about the invalid parameters and such when calling the callable, but that is not ideal.

This RFC tries to solve this problem by introducing implicit interface for callables.

Proposal

This RFC proposes to allow creating special interfaces which extend the “callable” type. A simple example could look like this:

interface MyCallable extends callable
{
    public function __invoke(string $foo) : int;
}

Now any function or method could typehint against MyCallable instead of callable and be certain that the parameters are accepted and the correct type is returned:

function foo(MyCallable $foo) : int
{
    return $foo('bar');
}
 
foo(function (string $foo) { return strlen($foo) });

Of course, this works with any other kind of callable as well, be it a string, an array or an object. Even with the object, it would not have to implement the interface, since it is considered a special one due to the extension of the “callable” type.

Since we do have an interface though, which technically represents a class, any callable would have to allow to be also invoked by calling $callable→__invoke().

Backward Incompatible Changes

This RFC expects no BC breaks.

Proposed PHP Version(s)

7.1

Proposed Voting Choices

This RFC requires a 2/3 majority to pass.

Patches and Tests

Patch will be available before voting commences.

Implementation

After the project is implemented, this section should contain

  1. the version(s) it was merged to
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature
rfc/typesafe-callable.1459807766.txt.gz · Last modified: 2017/09/22 13:28 (external edit)