On 04/19/2016 05:30 PM, Rowan Collins wrote:
Dmitry Stogov wrote on 19/04/2016 15:12:
I prefer intuitive concepts, that I may use without rereading manual
again and again.
For this one, I even can't imagine a natural (not over-designed) use
case.
The use case that came to my mind is kind of the other way around from
"syntax sugar for anonymous classes" - providing a contract for what a
callback should look like. In essence, it's an alternative to
specifying closure type with a generic-like syntax, as proposed at
https://wiki.php.net/rfc/callable-types
Say you currently have this:
public function registerCallback(callable $callback) { ... }
You could instead specify what the callback needs to accept and return:
interface EventCallbackInterface {
public function __invoke(Event $event): boolean;
}
public function registerCallback(EventCallbackInterface $callback) {
... }
Using __invoke as the method name may or may not be a good idea, but
it interestingly means I don't need to change the code that runs the
callback, I can just use $callback($some_event); Then if someone wants
to use a complex object, they can; and if they just want to use a
closure, it has to meet the contract.
callable-type is much simpler solution for this use-case.
Usage of Interfaces to check function prototypes is a bit tricky, but
yes, this is a possible use-case.
Do you like to work with framework, that use this trick for every callback?
Thanks. Dmitry.
Regards,
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php