Skip to content

Instantly share code, notes, and snippets.

@parweb
Forked from ramsey/variadic-generics.php
Created October 13, 2016 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parweb/55647686cb342b92c54c0951fd294201 to your computer and use it in GitHub Desktop.
Save parweb/55647686cb342b92c54c0951fd294201 to your computer and use it in GitHub Desktop.
You may type-hint on variadic functions in PHP to enforce type on elements in the array
<?php
class Foo {}
$f1 = new Foo();
$f2 = new Foo();
$bar = function (Foo ...$foo) {
foreach ($foo as $f) {
echo get_class($f) . "\n";
}
};
$bar($f1, $f2);
// Foo
// Foo
$bar($f1, 'bar', $f2);
// PHP Fatal error: Uncaught TypeError: Argument 2 passed to {closure}() must
// be an instance of Foo, string given
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment