Skip to content

Instantly share code, notes, and snippets.

@nyamsprod
Created December 12, 2024 10:31
Show Gist options
  • Save nyamsprod/ccc9b80a965fbfdd3e10da74aeec9da4 to your computer and use it in GitHub Desktop.
Save nyamsprod/ccc9b80a965fbfdd3e10da74aeec9da4 to your computer and use it in GitHub Desktop.
<?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