Closures and type hinting

From: Date: Fri, 12 Oct 2012 08:58:56 +0000
Subject: Closures and type hinting
Groups: php.internals 
Request: Send a blank email to internals+get-63368@lists.php.net to get a copy of this message
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?

« previous php.internals (#63368) next »