Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Type hint array arguments in PHP 5.6 using variadic functions and argument unpacking.
<?php
$run = function (callable ...$callables) {
foreach ($callables as $callable) {
$callable();
}
};
$callables = [
function () { echo 'Hello '; },
function () { echo 'World'; },
function () { echo '!' . PHP_EOL; },
];
$run(...$callables);
$callables = [
function () { echo 'Hello '; },
'World!' . PHP_EOL,
];
$run(...$callables);
~$ php docs/test.php
Hello World!
PHP Catchable fatal error: Argument 2 passed to {closure}() must be callable, string given
@sjparkinson

This comment has been minimized.

Copy link
Owner Author

commented Dec 8, 2015

Limitations

  • Array argument must be last in the method definition
  • Can't do scalar type hinting in 5.6
  • Raises an error, not a catchable exception (workaround is to throw an exception in the error handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.