PHP Conference Japan 2024

get_debug_type

(PHP 8)

get_debug_type取得適合用於除錯的變數類型名稱

說明

get_debug_type(混合 $value): 字串

傳回已解析的 PHP 變數 value 的名稱。此函式會將物件解析為其類別名稱、資源解析為其資源類型名稱,以及將純量值解析為其常用名稱,如同在類型宣告中使用的一樣。

此函式與 gettype() 的不同之處在於,它傳回的類型名稱與實際使用情況更一致,而不是基於歷史原因而存在的那些名稱。

參數

value

正在進行類型檢查的變數。

傳回值

傳回的 字串 的可能值如下:

類型 + 狀態 傳回值 備註
null "null" -
布林值 (truefalse) "bool" -
整數 "int" -
浮點數 "float" -
字串 "string" -
陣列 "array" -
資源 "resource (資源名稱)" -
資源 (已關閉) "resource (closed)" 範例:使用 fclose() 關閉後的檔案串流。
來自命名類別的物件 包含命名空間的完整類別名稱,例如 Foo\Bar -
來自匿名類別的物件 "class@anonymous" 或父類別名稱/介面名稱(如果該類別繼承另一個類別或實作一個介面),例如 "Foo\Bar@anonymous" 匿名類別是透過 $x = new class { ... } 語法建立的

範例

範例 #1 get_debug_type() 範例

<?php

namespace Foo;

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;

interface
A {}
interface
B {}
class
C {}

echo
get_debug_type(new class implements A {}), PHP_EOL;
echo
get_debug_type(new class implements A,B {}), PHP_EOL;
echo
get_debug_type(new class extends C {}), PHP_EOL;
echo
get_debug_type(new class extends C implements A {}), PHP_EOL;

?>

以上範例的輸出會類似於

null
bool
int
float
string
array
resource (stream)
resource (closed)
stdClass
class@anonymous
Foo\A@anonymous
Foo\A@anonymous
Foo\C@anonymous
Foo\C@anonymous

參見

新增註釋

使用者貢獻的筆記 1 則筆記

vyacheslav dot belchuk at gmail dot com
1 年前
此外,這個函式會返回正確的 Closure 類型,與 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 () => '');

?>

輸出

Closure
Closure

object(物件)
object(物件)
To Top