3v4l.org

run code in 500+ PHP versions simultaneously
<?php class X { } class Y { } function foo(X|Y|null $param, string|bool|null $anotherParam) { } class Z extends Y { } class U { } function isCompatibleWithType(string $type, mixed $value): bool { if (gettype($value) === 'object') { return get_class($value) === $type || is_subclass_of($value, $type); } return gettype($value) === $type; } function canAccept(callable $func, int $paramPosition, mixed $paramValue): bool { $r = new \ReflectionFunction($func); $canAccept = false; foreach ($r->getParameters() as $parameter) { if ($parameter->getPosition() !== $paramPosition) { continue; } $type = $parameter->getType(); if ($type instanceof \ReflectionUnionType) { foreach ($type->getTypes() as $t) { if (isCompatibleWithType($t->getName(), $paramValue) || ($t->allowsNull() && is_null($paramValue))) { return true; } } return false; } if ($type instanceof \ReflectionIntersectionType) { foreach ($type->getTypes() as $t) { if (!isCompatibleWithType($t->getName(), $paramValue)) /* intersection types do not support nullables for now */ { return false; } } return true; } return isCompatibleWithType($type->getName(), $paramValue) || ($t->allowsNull() && is_null($paramValue)); } return false; } var_dump(canAccept('foo', 0, null)); var_dump(canAccept('foo', 1, null));
Output for 7.4.0 - 7.4.33
Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /in/6AnNZ on line 7
Process exited with code 255.
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.34, 8.3.0 - 8.3.35, 8.4.1 - 8.4.26, 8.5.0 - 8.5.11
bool(true) bool(true)

preferences:
33.21 ms | 1140 KiB | 9 Q