Re: Closures and type hinting

From: Date: Sat, 13 Oct 2012 11:36:03 +0000
Subject: Re: Closures and type hinting
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-63392@lists.php.net to get a copy of this message
Am 12.10.2012 23:06, schrieb Nikita Popov:
On Fri, Oct 12, 2012 at 10:58 AM, Christian Kaps <christian.kaps@mohiva.com> wrote:
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?
Please also don't forget that PHP doesn't have strict function signatures. E.g. you can write
     function($foo) {
         echo $foo;
     }
but you could also write
     function() {
         $foo = func_get_arg(0);
         echo $foo;
     }
So I'm not sure just how much sense function signature checking makes in PHP ;) Nikita What did you mean with strict function signatures?
Is this not a strict function signature? function(Foo $foo) {} Christian

« previous php.internals (#63392) next »