PHP already has gettype() for getting type of a php variable. But It is kinda outdated. It returns type name that defined in PHP 5 era. In PHP 7, type system has improved much. To reflect that improved types, PHP 8 has introduced a new function get_debug_type() . It returns native type names and also resolves class names.
But, how is it any different from gettype()?
Lets find out with code...
$int = 1;
gettype($int);
// "integer"
get_debug_type($int);
// "int"
$float = 1.2;
gettype($float);
// "double"
get_debug_type($float);
// "float"
For historical reasons, gettype() returns double for float type. get_debug_type() returns the right type name.
$string = 'text';
gettype($string);
// "string"
get_debug_type($string);
// "string"
$bool = true;
gettype($bool);
// "boolean"
get_debug_type($bool);
// "bool"
$null = null;
gettype($null);
// "NULL"
get_debug_type($null);
// "null"
$array = [];
gettype($array);
// "array"
get_debug_type($array);
// "array"
$class = new stdClass();
gettype($class);
// "object"
get_debug_type($class);
// "stdClass"
get_debug_type() resolves class name for you automatically. Output will be identical to get_class().
$anonymousClass = new Class{};
gettype($anonymousClass);
// "object"
get_debug_type($anonymousClass);
// "class@anonymous"
get_debug_type() also reports anonymous class correctly.
$resource = tmpfile();
gettype($resource);
// "resource"
get_debug_type($resource);
// resource (stream)
As we can see, get_debug_type() also reports the type of the resource. If the resource is closed, it will return "resource (closed)"
Why do we need get_debug_type() ?
information about type of a variable can be needed for several task. It can be used for :
Yes, I have seen usage of type of a variable to execute some business logic. Such usage is common in weakly typed projects (read legacy project).
Write comment about this article: