Skip to content

Instantly share code, notes, and snippets.

@ramsey
Created October 13, 2016 17:38
Show Gist options
  • Save ramsey/67d4734e583fedf5d96d68296722de3e to your computer and use it in GitHub Desktop.
Save ramsey/67d4734e583fedf5d96d68296722de3e 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