Ở các phiên bản PHP trước, để lấy kiểu biến, dùng hàm gettype(). Hàm này trả về kiểu biến dưới dạng chuỗi. Các giá trị có thể: integer, string, array, boolean, double, resource, NULL, unknown type, v.v.
Tuy nhiên, gettype có vấn đề: không trả về tên kiểu gốc và quen thuộc. Trả về double thay vì float, integer thay vì int, v.v.
Để khắc phục, PHP 8 sử dụng hàm get_debug_type.
Hàm get_debug_type()
Trong PHP 8, get_debug_type trả về kiểu gốc thực sự của biến. Trả về float, int thay vì double, integer. Hàm tự động giải tên lớp của đối tượng.
get_debug_type() hỗ trợ:
Gỡ lỗi (debugging)
Logic nghiệp vụ
Báo cáo lỗi
Ví dụ: Dùng gettype() trong 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));
}
?>
Kết quả
Expected Comment still got MyNovel
Ví dụ: Dùng get_debug_type() trong 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);
}
?>
Kết quả
Expected Comment still got MyNovel