CakeFest 2024: The Official CakePHP Conference

get_debug_type

(PHP 8)

get_debug_type以适合调试的方式获取变量的类型名称

说明

get_debug_type(mixed $value): string

会返回 PHP 变量 value 的类型名称。 该函数会将对象解析为其类名,资源解析为其资源类型名称,标量值解析为其常用名称,就像在类型声明中使用的那样。

该函数与 gettype() 的区别在于:它返回的类型名称更符合实际用法,而不是那些出于历史原因而存在的名称。

参数

value

要检查类型的变量。

返回值

返回的字符串可能有以下值:

类型 + 状态 返回值 备注
null "null" -
Booleans (true or false) "bool" -
Integers "int" -
Floats "float" -
Strings "string" -
Arrays "array" -
Resources "resource (resourcename)" -
Resources (Closed) "resource (closed)" 例如:使用 fclose 关闭后的文件流
Objects from Named Classes 类的全名,包括其命名空间,例如 Foo\Bar -
Objects from Anonymous Classes "class@anonymous" 匿名类是通过 $x = new class { ... } 语法创建的类

示例

示例 #1 get_debug_type() 示例

<?php
echo get_debug_type(null) . PHP_EOL;
echo
get_debug_type(true) . PHP_EOL;
echo
get_debug_type(1) . PHP_EOL;
echo
get_debug_type(0.1) . PHP_EOL;
echo
get_debug_type("foo") . PHP_EOL;
echo
get_debug_type([]) . PHP_EOL;

$fp = fopen(__FILE__, 'rb');
echo
get_debug_type($fp) . PHP_EOL;

fclose($fp);
echo
get_debug_type($fp) . PHP_EOL;

echo
get_debug_type(new stdClass) . PHP_EOL;
echo
get_debug_type(new class {}) . PHP_EOL;
?>

以上示例的输出类似于:

null
bool
int
float
string
array
resource (stream)
resource (closed)
stdClass
class@anonymous

参见

add a note

User Contributed Notes 1 note

up
3
vyacheslav dot belchuk at gmail dot com
4 months ago
Also, the function returns the correct type of Closure, as opposed to gettype()

<?php

echo get_debug_type(function () {}) . PHP_EOL;
echo
get_debug_type(fn () => '') . PHP_EOL . PHP_EOL;

echo
gettype(function () {}) . PHP_EOL;
echo
gettype(fn () => '');

?>

Output:

Closure
Closure

object
object
To Top