At the moment it isn't possible to restrict/define the arguments for a closure which is defined as parameter for a method. Please look at this small example.

interface Broker {

    public function scan(Request $request, Closure $onFound);
}

An implementation of the interface could be as follows:

class BrokerImpl implements Broker {

    /**
     * @var Service
     */
    private $service = null;

    public function scan(Request $request, Closure $onFound) {

        if ($request->contains('some value')) {
            $onFound($this->service);
        }
    }
}

The problem is that I can pass every closure to the scan method.

$broker = new BrokerImpl();
$broker->scan($request, function() { /* do something */ });

Sometimes I would like to restrict the closure passed to this method. So that only closures of a certain type which has an argument "Service $service" could be passed to this method.

$broker = new BrokerImpl();
$broker->scan($request, function(Service $service) { /* do something */ });

Would it not be possible to extend the Closure class and then define an abstract method signature for the __invoke method.

class OnFoundClosure extends Closure {

    public abstract function __invoke(Service $service);
}

And then you can define the interface as follows:
interface Broker {

    public function scan(Request $request, OnFoundClosure $onFound);
}

Now if you pass a closure to the scan method which doesn't follow the signature of the __invoke method, the engine should throw an error.

What do you think?

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to