Skip to content

Instantly share code, notes, and snippets.

@dave1010
Created April 29, 2014 08:07
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 dave1010/11393640 to your computer and use it in GitHub Desktop.
Save dave1010/11393640 to your computer and use it in GitHub Desktop.
Type hinting in PHP variadics
<?php
class Bar{}
$bars = [new Bar, new Bar, new Bar];
$ints = [1, 2, 3];
// without variadics
// lots of manual type checking
function oldFoo($bars)
{
foreach ($bars as $bar) {
if (!$bar instanceof Bar) {
throw new InvalidArgumentException("Must be a Bar.");
}
}
echo "Got " . count($bars) . " bars.\n";
}
// php 5.6 style
// just look at this lovely type checking!
function foo(Bar ...$bars)
{
echo "Got " . count($bars) . " bars.\n";
}
foo(...$bars);
// fatal error
foo(...$ints);
oldFoo($bars);
// InvalidArgumentException
oldFoo($ints);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment