Created
December 12, 2024 10:31
-
-
Save nyamsprod/ccc9b80a965fbfdd3e10da74aeec9da4 to your computer and use it in GitHub Desktop.
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 FoobarWithReflectionCall | |
{ | |
public static function staticMethod(int|float $value): int|float | |
{ | |
return $value; | |
} | |
public static function __callStatic(string $name, array $arguments): int|float|null | |
{ | |
if (!str_starts_with($name, 'try')) { | |
throw new BadMethodCallException("static method $name does not exist."); | |
} | |
$method = lcfirst(substr($name, 3)); | |
if (!method_exists(self::class, $method)) { | |
throw new BadMethodCallException("static method $name does not exist."); | |
} | |
$reflection = new ReflectionMethod(self::class, $method); | |
if (!$reflection->isPublic() || !$reflection->isStatic()) { | |
throw new BadMethodCallException("static method $name does not exist."); | |
} | |
try { | |
return $reflection->invoke(null, ...$arguments); | |
} catch (Throwable) { | |
return null; | |
} | |
} | |
} | |
class FoobarWithoutReflectionCall | |
{ | |
public static function staticMethod(int|float $value): int|float | |
{ | |
return $value; | |
} | |
public static function __callStatic(string $name, array $arguments): int|float|null | |
{ | |
if (!str_starts_with($name, 'try')) { | |
throw new BadMethodCallException("static method $name does not exist."); | |
} | |
$method = lcfirst(substr($name, 3)); | |
if (!method_exists(self::class, $method)) { | |
throw new BadMethodCallException("static method $name does not exist."); | |
} | |
$reflection = new ReflectionMethod(self::class, $method); | |
if (!$reflection->isPublic() || !$reflection->isStatic()) { | |
throw new BadMethodCallException("static method $name does not exist."); | |
} | |
try { | |
return $method(...$arguments); | |
} catch (Throwable) { | |
return null; | |
} | |
} | |
} | |
var_dump( | |
FoobarWithReflectionCall::tryStaticMethod('42'), // returns 42 | |
FoobarWithoutReflectionCall::tryStaticMethod('42'), // returns null | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment