ใน PHP เวอร์ชันก่อนหน้า หากเราต้องการรับประเภทของตัวแปร เราเคยใช้ฟังก์ชัน gettype() ฟังก์ชันนี้คืนค่าประเภทของตัวแปรในรูปแบบสตริง คืนค่าที่เป็นไปได้ทั้งหมด เช่น integer, string, array, boolean, double, resource, NULL, unknown type ฯลฯ
อย่างไรก็ตาม มีปัญหาในฟังก์ชัน gettype มันไม่คืนค่าชื่อประเภทพื้นฐานและที่คุ้นเคย มันคืนค่า double แทน float และ integer แทน int ฯลฯ
เพื่อแก้ปัญหานี้ PHP 8 ใช้ฟังก์ชัน get_debug_type
ฟังก์ชัน get_debug_type()
ใน PHP 8 ฟังก์ชัน get_debug_type คืนค่าประเภทพื้นฐานที่แท้จริงของตัวแปร คืนค่า float, int แทน double และ integer ฟังก์ชันนี้จะ resolve ชื่อคลาสของอ็อบเจกต์โดยอัตโนมัติ
get_debug_type() ช่วยใน
การดีบัก (debugging)
ตรรกะทางธุรกิจ (business logic)
การรายงานข้อผิดพลาด (error reporting)
ตัวอย่าง: ใช้ฟังก์ชัน gettype() ใน PHP
<?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
ตัวอย่าง: ใช้ฟังก์ชัน get_debug_type() ใน 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