rfc:typesafe-callable

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 user-defined callables.

Proposal

This RFC proposes the definition of user-defined callables. Since “callable” is already a reserved keyword, this should not be a BC break. User-defined callables should be be both allowed to be namespaced like functions and classes, but also invoke the autoloader if they are not found in the current scope. A simple callable definition could look like this:

callable FilterCallable(string $input) : string;

With such a callable in place, the user can now typehint against it, like they would against any other property, and be certain that it will accept the parameters they pass in, as well as guarantee the return type they expect:

function foo(FilterCallable $filter) : string
{
    return $filter('bar');
}
 
foo(function (string $foo) : string { return trim($foo); });

Of course, this works with any other kind of callable as well, be it a string, an array or an object.

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.txt · Last modified: 2017/09/22 13:28 (external edit)