get_debug_type

get_debug_type($value)

Returns the type of a value the way it is written in type declarations: int, float, string, bool, null, array, for an object the class name. It is useful in error messages. The function has been available since PHP 8.0.

Parameters

  • $value – the value to examine.

Examples

echo get_debug_type(42); // int
echo get_debug_type(4.2); // float
echo get_debug_type(true); // bool
echo get_debug_type(null); // null
echo get_debug_type(array(1, 2)); // array
echo get_debug_type(new DateTime()); // DateTime
echo get_debug_type(function () {}); // Closure
echo get_debug_type(new class {}); // class@anonymous
// a file opened and closed
$f = fopen("php://memory", "r");
echo get_debug_type($f); // resource (stream)
fclose($f);
echo get_debug_type($f); // resource (closed)
// gettype() for comparison
echo gettype(4.2); // double
echo gettype(new DateTime()); // object
// a clear error message
function set_quantity($quantity) {
    if (!is_int($quantity)) {
        throw new InvalidArgumentException("Quantity must be int, got " . get_debug_type($quantity));
    }
}
try {
    set_quantity("5");
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // Quantity must be int, got string
}

Fallback for older PHP

The function does not exist in versions older than PHP 8.0. The following code adds it only where it is missing, newer versions use the built-in function.

if (!function_exists("get_debug_type")) {
    function get_debug_type($value) {
        if ($value === null) {
            return "null";
        }
        $names = array("boolean" => "bool", "integer" => "int", "double" => "float", "string" => "string", "array" => "array");
        $type = gettype($value);
        if (isset($names[$type])) {
            return $names[$type];
        }
        if (is_object($value)) {
            $class = get_class($value);
            return strpos($class, "@anonymous") !== false ? "class@anonymous" : $class;
        }
        return $type === "resource" ? "resource (" . get_resource_type($value) . ")" : "resource (closed)";
    }
}
echo get_debug_type(4.2); // float
echo get_debug_type(new DateTime()); // DateTime

Things to watch out for

  • The names differ from gettype(): int instead of integer, float instead of double, bool instead of boolean, null instead of NULL. For an object it returns the class name, gettype() only object.
  • The function is meant for messages and debugging. For decisions in code use is_int(), is_string() or instanceof.
  • An anonymous class that extends another class is printed as "ParentClass@anonymous". The fallback above always returns class@anonymous.

Related functions:
gettype()
get_class()
is_object()
var_dump()