Re: Closures and type hinting
| From: | Anthony Ferrara | Date: | Fri, 12 Oct 2012 09:18:42 +0000 |
| Subject: | Re: Closures and type hinting | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-63369@lists.php.net to get a copy of this message | ||
On Oct 12, 2012 10:59 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?
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
Honestly, I would suggest using a class directly if you want that kind of
type control. Closures are meant to be a conscience, not the end all be all
implementation.
I understand what you are looking for. But to me, unless we implemented
function pointers (typeable callbacks), I can't see the generalized use
case. At least that isn't already solvable using classes, interfaces and
polymorphism...
Anthony