If we don't type hint variadic arguments we get this following type checker error.
Was expecting a type hint (what about: array)
If we do type hint them, the type checker error goes away, but then we get this runtime error.
Fatal error: Parameter $args is variadic and has a type constraint (array); variadic params with type constraints are not supported
What's the best way to go about this?
The runtime doesn't have full support for variadics yet (they can't be typed). The main concern is that in PHP 5.6 type-checking a variadic requires looping over the variadic array to check each argument. We plan to add support for this, but in the meantime if you want to use strict mode with variadics you'll need to add an HH_FIXME,
function foo(
int $arg1,
bool $arg2,
/* HH_FIXME[4033]: variadic + strict */ ...$args
): string {
// ...
}
Had a chat with @dlreeves and @sgolemon; we're likely to:
I'm curious what's expensive about it? It seems like a basic O(N) problem, which _shouldn't_ be too large, usually under 10 items.
an O(n) problem at runtime is a large perf issue in the context of HHVM.
True, but it seems like variadic arguments would be so sparse, that the cost incursion would be relatively minor. Coming from an outside perspective at least.
It's also almost unnecessary in Hack (same exceptions as generics), and it would be weird to have different validation behavior for Hack and PHP.
If PHP 7 supports it, you have to support it eventually.
HH_FIXME[4033] doesn't work for type hinted variadics:
$ cat test.php
<?php
function test(/* HH_FIXME[4033] */ int ...$numbers) {
echo array_sum($numbers);
}
test(1, 2, 3);
$ hhvm test.php
Fatal error: Parameter $numbers is variadic and has a type constraint (int); variadic params with type constraints are not supported in /path/to/test.php on line 3
$ php test.php
6
Any thoughts on how to remedy this?
Btw, real world usage of variadic callables: https://github.com/lstrojny/functional-php/blob/master/src/Functional/Compose.php
Closing - supported in '
@mschwager, @lstrojny : #6954
@mschwager : HH_FIXME has no runtime affects; it only affects the Hack typechecker, and your code isn't hack.
Most helpful comment
If PHP 7 supports it, you have to support it eventually.