Hello Hamza, I think this is something that has been discussed here before.
function types already exist in HackLang: https://docs.hhvm.com/hack/functions/introduction#function-types, And, if we would follow the same syntax `(function(T, T): T)` or `(callable(T, T): T)`, PHP needs to first support parentheses in type declaration ( grouping ), which currently it doesn't ( i.e: `function baz((string|bar) $foo): void {}` becomes valid ). And just to note, function types are also supported by static analysis tools such as Psalm ( https://psalm.dev/docs/annotating_code/type_syntax/callable_types/ ) and PHPStan ( https://phpstan.org/writing-php-code/phpdoc-types#callables ), so i suppose if PHP is to support typed callables, it should take inspiration from these tools. There's also an alternative syntax that was proposed back in 2016 for PHP 7.1, but it seems like the RFC was abandoned: https://wiki.php.net/rfc/typesafe-callable Cheers, Saif. ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐ On Wednesday, April 7, 2021 11:58 AM, Hamza Ahmad <office.hamzaah...@gmail.com> wrote: > Hello Internals, > I want to request making possible to catch functions with wrong signature > when passed as callable. In other words, when a function or a method is > passed as callable value, PHP will first confirm whether the function is of > the write callable type that the function being executed requires. It will > help catch silent errors. > Currently, PHP does following: > > 1. Confirms whether a callable is valid. > 2. Passes the callable value to a function, and the execution starts. > 3. If the passed function receives values which's type is different than > function signature, PHP throws an error. > > 4. If passed function returns nothing, the variable that wanted a value from > the passed function receives null. > > 5. As a result, the unexpected results emerge. > To resolve this issue, I propose to introduce a mechanism that allows to > hint callable signatures. To understand the spirit of this request, look > at > the similar functionality that Angel Script Project provides with. > > 6. One defines a function definition. > 7. Use its name to hint the same signature. > 8. The compiler alerts about the incorrect signature before passing this to > a function. > If I could do this in PHP, I would write like following: > `funcdef preg_replace_callback_hint(array $matches) : string;` > If I accidently pass a callable which's signature is different than > desired > function call, the error is caught earlier. > This message does not suggests syntax; it only points to a problem and > suggests a solution. Any volunteers that would love to come up with syntax > and implement this? > I am curious to see the feedback. > Regards > Hamza Ahmad > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: https://www.php.net/unsub.php >
signature.asc
Description: OpenPGP digital signature