Closure Type Hint with __invoke

I've seen that type hinting with `__invoke` interfaces works as return values. But then quickly realized, that it doesn't work on the input side.

Is it possible to fix that?

Example:

interface ClosureInterface
{
    public function __invoke(string $string, int $int): ?bool;
}

function acceptClosure(ClosureInterface $closure)
{
}

// Doesn't work:
// Expected ClosureInterface, got Closure
acceptClosure(function ($string, $int) {
    return true;
});

function returnClosure(): ClosureInterface
{
    // Doesn't work:
    // Return value is expected to be 'ClosureInterface', '\Closure' returned
    return function ($string, $int) {
        return true;
    };
}

// This works, it typehints: 'string : string, int : int'
returnClosure()('string', 1);
2 comments
Comment actions Permalink

Please use PhpDocs for that:

interface ClosureInterface {

  public function __invoke(string $string,
                           int $int): ?bool;
}

/**
 * @param Closure|\ClosureInterface $closure
 */
function acceptClosure(ClosureInterface $closure) {
}

// Doesn't work:
// Expected ClosureInterface, got Closure
acceptClosure(function ($string,
                        $int) {
  return TRUE;
});
/**
 * @return Closure|\ClosureInterface
 */
function returnClosure(): ClosureInterface {
  // Doesn't work:
  // Return value is expected to be 'ClosureInterface', '\Closure' returned
  return function ($string,
                   $int) {
    return TRUE;
  };
}

// This works, it typehints: 'string : string, int : int'
returnClosure()('string',
  1);
0
Comment actions Permalink

With this change you just allow any Closure and you don't get any type hint for the given parameters or the return type.

0

Please sign in to leave a comment.