Difference between gettype() in PHP and get_debug_type() in PHP 8

PHPServer Side ProgrammingProgramming

In the earlier versions of PHP, if we wanted to get the type of a variable, we used to employ the gettype() function. This function returns the type of a variable in the custom of a string. It returns all possible values like integer, string, array, boolean, double, resource, NULL, unknown type, etc.

However, there were issues in the gettype function. It does not return native and familiar type names. It returns double instead of float and integer instead of int, and so on.

To overcome this problem, PHP 8 uses the get_debug_type function.

get_debug_type() function

In PHP 8, the get_debug_type function returns the true native type of variables. It returns a float, int instead of double and integer. This function automatically resolves the class names of objects.

get_debug_type() function helps in

  • debugging

  • business logic

  • error reporting

Example: using gettype() function in PHP

 Live Demo

<?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));
   }
?>

Output

Expected Comment still got MyNovel

Example : Using get_debug_type() function in 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);
   }
?>

Output

Expected Comment still got MyNovel
raja
Published on 01-Apr-2021 06:43:51
Advertisements