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:
Type | Value | gettype | get_debug_type |
---|---|---|---|
Null | null | NULL | null |
Integer | 1 | integer | int |
Floating-point number | 0.5 | double | float |
Boolean | true or false | boolean | bool |
String | Hi | string | string |
Array | [1, 2] | array | array |
Instance of standard class | new stdClass() | object | stdClass |
Instance of built-in class | new Exception() | object | Exception |
Instance of user-defined class | new App\Entity\User() | object | App\Entity\User |
Instance of anonymous class | new class() {} | object | class@anonymous |
Instance of anonymous subclass | new class() extends Exception {} | object | Exception@anonymous |
Anonymous function | function() {} | object | Closure |
Generator | (function() { yield 1; })() | object | Generator |
Resource | fopen('test.txt', 'rb') | resource | resource (stream) |
Closed resource | $f = fopen('test.txt', 'rb'); fclose($f); | resource (closed) | resource (closed) |
Leave a Comment
Cancel reply