PHP 8.0: ReflectionParameter::getClass())
, ::isArray()
, and ::isCallable()
methods deprecated
PHP 8 introduces several improvements in PHP type systems such as the introduction of Union Types, mixed
type, and a few more.
With these changes, certain methods in Reflection API's ReflectionParameter
yield incorrect results.
In PHP 8, the following methods from ReflectionParameter
class is deprecated:
ReflectionParamter::getType()
is the recommended way to replace the deprecated methods. This method is available in PHP 7.0 and later.
ReflectionParameter::getClass()
deprecation
Trying to use ReflectionParameter::getClass()
will emit a deprecation notice in PHP 8:
Deprecated: Function ReflectionParameter::getClass() is deprecated in ... on line ...
ReflectionParameter::getClass()
returns the name of the class of a parameter. However, when a Union Type is used, it returns null
if difference class types are in a single Union.
ReflectionParameter::getType()
supersedes getClass()
method. Note that getClass()
method returns a ReflectionClass()
object, which implements __toString()
. If you are interested in just the name, you can use $param->getType()->getName()
to return the name.
A full replacement with same functionality:
- $name = $reflectionParam->getClass();
+ $name = $param->getType() && !$param->getType()->isBuiltin()
+ ? new ReflectionClass($param->getType()->getName())
+ : null;
ReflectionParameter::isArray()
deprecation
ReflectionParameter::isArray()
is deprecated in PHP 8 because it only works with array
and ?array
types, but not with a Union type.
ReflectionParameter::getType()
result can be used to mimic the result of this method:
- $isArray = $param->isArray();
+ $isArray = $param->getType() && $param->getType()->getName() === 'array';
ReflectionParameter::isCallable()
deprecation
ReflectionParameter::isCallable()
is deprecated in PHP 8 too, and similar to isArray()
, it only works for callable
and ?callable
parameters, but not when it's used in a Union Type.
ReflectionParameter::getType()
result can be used to mimic the result of this method for isCallable
as well:
- $isCallable = $param->isCallable();
+ $isCallable = $param->getType() && $param->getType()->getName() === 'callable';
Backwards compatibility impact
All 3 deprecated methods can be easily replaced with the result of getType()
method, which is more robust and accurate in PHP 8. getType()
method is available in PHP 7.0 and later.
If you need your code to work in PHP 5, through 8, conditional code branches depending on the PHP version can be used. For all other cases, replacing the deprecated method with getType()
approaches will be backwards compatible to all PHP 7 versions as well.