Last active
February 16, 2020 04:45
-
-
Save sshymko/c3780dbe47880edf442339a7e931ea95 to your computer and use it in GitHub Desktop.
PHP7 function/method signature overloading
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 | |
declare(strict_types=1); | |
function overload(callable ...$implementations): callable | |
{ | |
return function (...$args) use ($implementations) { | |
$error = new \LogicException('Invalid overloaded implementations'); | |
foreach ($implementations as $candidate) { | |
try { | |
return $candidate(...$args); | |
} catch (\TypeError $e) { | |
$error = $e; | |
} | |
} | |
throw $error; | |
}; | |
} |
Released the overloading implementation as a Composer package:
https://github.com/upscalesoftware/stdlib-overloading
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example:
Note: declare longer signatures before ones with subset of arguments of matching types.