Get Type of Variable using get_debug_type in PHP 8.0

Get Type of Variable using get_debug_type in PHP 8.0

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

Since PHP 8.0, we can use the 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).

<?php

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:

TypeValuegettypeget_debug_type
NullnullNULLnull
Integer1integerint
Floating-point number0.5doublefloat
Booleantrue or falsebooleanbool
StringHistringstring
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');
fclose($f);
resource (closed)resource (closed)

Leave a Comment

Cancel reply

Your email address will not be published.