PHP 中 gettype() 與 PHP 8 中 get_debug_type() 的區別


在早期的 PHP 版本中,如果我們想獲取變數型別,通常使用gettype()函式。該函式以字串形式返回變數型別。它返回所有可能的值,如整數、字串、陣列、布林值、浮點數、資源、NULL、未知型別等。

但是,gettype函式存在問題。它不返回本機和熟悉的型別名稱。它返回浮點數而不是浮點數,返回整數而不是 int 等。

為了解決此問題,PHP 8 使用get_debug_type函式。

get_debug_type() 函式

在 PHP 8 中,get_debug_type 函式返回變數的真實本機型別。它返回浮點數、int 而不是浮點數和整數。此函式自動解析物件類名稱。

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

示例 : 在 PHP 8 中使用 get_debug_type() 函式

<?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

更新時間: 2021 年 4 月 1 日

317 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.