Skip to content

Instantly share code, notes, and snippets.

@sjparkinson
Last active February 12, 2024 10:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjparkinson/517cabd36023fecbf70e to your computer and use it in GitHub Desktop.
Save sjparkinson/517cabd36023fecbf70e to your computer and use it in GitHub Desktop.
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
Copy link
Author

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