Get Type of Variable using get_debug_type in PHP 8.0

PHP has gettype function that allows to get the type of a variable. This function can be useful for debugging, testing, creating error messages, etc.

Since PHP 8.0, we can use get_debug_type function that is similar to gettype function. The get_debug_type function returns native type names (e.g. bool instead of boolean) and resolves class names (e.g. stdClass instead of object).


echo gettype(false);                 // boolean
echo get_debug_type(false);          // bool

echo gettype(new stdClass());        // object
echo get_debug_type(new stdClass()); // stdClass

The following table shows differences between these two functions:

Floating-point number0.5doublefloat
Booleantrue or falsebooleanbool
Array[1, 2]arrayarray
Instance of standard classnew stdClass()objectstdClass
Instance of built-in classnew Exception()objectException
Instance of user-defined classnew App\Entity\User()objectApp\Entity\User
Instance of anonymous classnew class() {}objectclass@anonymous
Instance of anonymous subclassnew class() extends Exception {}objectException@anonymous
Anonymous functionfunction() {}objectClosure
Generator(function() { yield 1; })()objectGenerator
Resourcefopen('test.txt', 'rb')resourceresource (stream)
Closed resource$f = fopen('test.txt', 'rb');
resource (closed)resource (closed)

Leave a Comment

Your email address will not be published. Required fields are marked *