Typed callable properties
| From: | moliata | Date: | Tue, 21 Apr 2020 11:14:28 +0000 |
| Subject: | Typed callable properties | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-109748@lists.php.net to get a copy of this message | ||
Hey internals,
I wanted to ignite a friendly discussion whether PHP should allow typed callable properties. The
problem arises as typed properties RFC did not allow the callable type [1] due to its
context-dependent behaviour. As such, for improving the language's consistency and adding
support for strict callable typing, I believe we should look into solutions for avoiding this
special case. Note that the solutions listed below are taken from the RFC and are thoughts from
Nikita Popov, so credits to him. Here is a quick summary of the solutions:
1. Ignore the issue. At the moment, this is the behaviour that both parameter and return type hints
pose and I believe is also the best option for callable properties. At least for the time being.
Generally, this would increase language's consistency and would also ensure that the type is
actually *a* callable. In the worst-case scenario, if the callable is not callable from this
context, PHP would still throw a runtime error.
2. Take visibility into account. We could allow making only typed protected/private callable
properties but this would create a quite tight coupling between the visibility and type. It would
also be a special case and therefore a violation of the OCP principle.
3. We could automatically wrap assignments to typed callable properties into
Closure::fromCallable(). Though this would worsen the performance and add additional
overhead when using the callable type. As Nikita mentioned, if this is the approach we're
taking, we should also impose such conversion in every place where the callable type may occur.
4. Perform type checks when reading. At the moment, we perform type checks only when writing. We
could change that and also perform type checks when reading. Although this behaviour would be weird,
as we would get a type error when trying to read a typed callable property (e. g.
($this->callback)() would throw a type error).
[1]: https://wiki.php.net/rfc/typed_properties_v2#callable_type
Best regards,
Benas Seliuginas
P.S.: If no one is interested in implementing this, I would be up for the job if we make a consensus
on what approach we should take.