On Thu, Apr 13, 2023 at 6:00 AM Eugene Sidelnyk <zsidel...@gmail.com> wrote:
>
> Hello, internals! I just want to share some thoughts with you regarding
> what could be improved in the first class callable syntax.
>
> It is already possible to create Callable from a static method:
>
> ```
> class Foo {
> public static function staticmethod() {}
> }
>
> $c = Foo::staticmethod(...);
> ```
>
> It would be a great pleasure to have the ability to wrap the instance
> method the same way. One particular use case for this could be when there's
> an array of items and it is necessary to call some getter-method on all of
> them.
>
> ```
> class Verification
> {
> public function __construct(private string $id) {}
>
> public function getId(): string
> {
> return $this->id;
> }
> }
>
> $items = [new Verification('1-2-3-4')];
>
> array_map(Verification::getId(...), $items);
>
> // previous line is an equivalent of this
> array_map(static fn (Verification $v) => $v->getId(), $items);
> ```
>
> Currently this syntax fails in run-time rather than compile-time.
>
> ```
> PHP Fatal error:  Uncaught Error: Non-static method Verification::getId()
> cannot be called statically in /opt/scratches/scratch_439.php:21
> ```
>
> Please, let me know what you think about it.
>
> Best regards, Yeven

Hello,

This has been brought up a couple of times, but I can't seem to find
it. I don't think something like this is possible with the current
implementation of first-class-callables (it would need a major
refactor). Currently adding the callable bit like `func(...)` is
roughly the same as just writing a string `'func'` and passing that
around (IIRC, that's literally what it gets turned to after parsing).
The only difference over using a string, is that there is some
validation to check that it is actually a function you can call.

Basically, there's currently no way to do something like what you
suggest in the engine, which makes it quite a big feature. That being
said, we shouldn't be afraid of doing hard things, but it would be a
lot of work for saving just a few characters of typing every now and
then.

Perhaps it would be easier after partial application could be
implemented (latest discussion here:
https://externals.io/message/119678#119678), or maybe someone else has
some better ideas or thoughts.

Cheers,

Rob Landers
Utrecht, Netherlands

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to