PHP 中的 gettype() 与 PHP 8 中的 get_debug_type() 之间的区别
phpserver side programmingprogramming更新于 2025/11/17 19:32:00
在 PHP 的早期版本中,如果我们想要获取变量的类型,我们过去常常使用 gettype() 函数。此函数以字符串的形式返回变量的类型。它返回所有可能的值,如整数、字符串、数组、布尔值、双精度、资源、NULL、未知类型等。
但是,gettype 函数存在问题。它不返回本机和熟悉的类型名称。它返回 double 而不是 float,返回 integer 而不是 int,等等。
为了解决这个问题,PHP 8 使用了 get_debug_type 函数。
get_debug_type() 函数
在 PHP 8 中,get_debug_type 函数返回变量的真正本机类型。它返回浮点数、int 而不是 double 和 integer。此函数自动解析对象的类名。
get_debug_type() 函数有助于
调试
业务逻辑
错误报告
示例:在 PHP 中使用 gettype() 函数
<?php
class Novel {}
class Comments {}
$novel = new Novel();
if(! ($novel instanceof Comment)) {
echo 'Expected ' . Comment::class . ' still got My' . (is_object($novel) ?
get_class($novel) : gettype($novel));
}
?>
输出
Expected Comment still got MyNovel
Example : Using get_debug_type() function in PHP 8
<?php
class Novel {}
class Comments {}
$novel = new Novel();
if(! ($novel instanceof Comment)) {
echo 'Expected '.Comment::class.' still got My'.get_debug_type($novel);
}
?>
输出
Expected Comment still got MyNovel

