Created
April 29, 2014 08:07
-
-
Save dave1010/11393640 to your computer and use it in GitHub Desktop.
Type hinting in PHP variadics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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