Re: Closures and type hinting
| From: | Christian Kaps | Date: | Sat, 13 Oct 2012 11:31:08 +0000 |
| Subject: | Re: Closures and type hinting | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-63391@lists.php.net to get a copy of this message | ||
Hi
I thought it would be a good idea to make the closure functionality consistent with the rest of the language. Because closures are currently implemented as class. And with classes it is possible to define static type checks at runtime. The other thing is that I can define a static type control for closures. It works only the other way around. Because the caller can define the static type control and not the interface designer. $closure = function(Foo $foo, Bar $bar) {}; function execute(Closure $closure) {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?You are trying to take typing way beyond what PHP (or probably any mainstream dynamic language that exists now) provides. There are languages which provide static type systems capable of doing such things, but PHP isn't one of them and I don't think it should be. PHP has no static type control, and IMHO doing type safety validation at runtime does not seem to be a good proposition for PHP.
$closure(1, 2);} execute($closure); // PHP Catchable fatal error: Argument 1 passed to {closure}() must be an instance of Foo, integer given Normally as interface designer I would like to define what a caller of the interface should be passed to a certain method. Yes I know with primitive types, this isn't possible in PHP. But with closure I have the option to restrict the interface. Sure I can do this only for one type of a closure. Quasi the the smallest common denominator. But it's possible. So when we look at the above example then it throws an error, because the caller passes the wrong type of a closure to the interface. But what is wrong, I have passed a closure to the method! So it seems that the interface lies. And for me this is the inconsistency in the implementation. I cannot tell the caller, what type of closure he must pass to the interface. And yes, for me a closure can be of a different type. If closures have different parameter signatures than they are of a different type. But this is only my subjective opinion. And I'm guessing by the reactions of my post that I'm all alone with it (o; Cheers, Christian