Created
September 8, 2020 12:27
-
-
Save vertexvaar/01ae93a28f04c941cb40f02518aaf977 to your computer and use it in GitHub Desktop.
"Java isn't that complicated, you can build it with PHP" - Sorin
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 Magic | |
{ | |
public function add() | |
{ | |
$args = func_get_args(); | |
$count = count($args); | |
$methods = []; | |
$refl = new ReflectionClass(static::class); | |
foreach ($refl->getMethods() as $method) { | |
if (0 === strpos($method->getName(), '_' . __FUNCTION__ . '_') | |
&& $method->getNumberOfParameters() === $count | |
) { | |
$methods[] = $method; | |
} | |
} | |
$types = array_map('gettype', $args); | |
foreach ($methods as $method) { | |
$params = $method->getParameters(); | |
$paramTypes = []; | |
foreach ($params as $param) { | |
$paramTypes[$param->getPosition()] = $param->hasType() ? $this->normalize($param->getType()->getName()) : 'mixed'; | |
} | |
if ($types === $paramTypes) { | |
return call_user_func_array([$this, $method->getName()], $args); | |
} | |
} | |
} | |
private function normalize(string $type) | |
{ | |
switch ($type) { | |
case 'int': | |
return 'integer'; | |
default: | |
return $type; | |
} | |
} | |
private function _add_1($a) | |
{ | |
return $a; | |
} | |
private function _add_2_a(string $a, int $b) | |
{ | |
return $a + $b; | |
} | |
private function _add_2_b(int $a, string $b) | |
{ | |
return $a + $b; | |
} | |
private function _add_3(...$numbers) | |
{ | |
return array_reduce( | |
$numbers, | |
'add', | |
0 | |
); | |
} | |
} | |
function add($a, $b): int | |
{ | |
return $a + $b; | |
} | |
$a = $b = $c = 2; | |
$obj = new Magic(); | |
echo $obj->add("4", 56); | |
echo $obj->add(42, "88"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment