Getting the type name of a variable for debugging with PHP

Published on 2022-04-23 • Modified on 2022-04-23

This snippet shows how to get the type name of a variable for debugging. The get_debug_type() function was introduced in PHP 8 and isn't well known yet. Before, we had to use the gettype() function. To understand the differences between both, I display both outputs. As we can see, get_debug_type() is especially useful for objects where the name of the class is displayed instead of the general object type.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet199Trait
{
    public function snippet199(): void
    {
        /** @var resource $fp */
        $fp = fopen(__FILE__, 'rb');
        /** @var resource $fpClosed */
        $fpClosed = fopen(__FILE__, 'rb');
        fclose($fpClosed);

        $variables = [
            'null' => null,
            'true' => true,
            'false' => false,
            '555' => 555,
            '0.5' => 0.5,
            "'foo'" => 'foo',
            "['foo' => 'bar']" => ['foo' => 'bar'],
            '$fp' => $fp,
            '$fpClosed' => $fpClosed,
            '$this' => $this,
            'new class {}' => new class() {}, // @phpstan-ignore-line, false positive
            'function() {}' => static function () {},
        ];

        foreach ($variables as $code => $variable) {
            echo 'get_debug_type('.$code.') = '.get_debug_type($variable).PHP_EOL;
            echo 'gettype('.$code.') = '.\gettype($variable).PHP_EOL.PHP_EOL;
        }
        fclose($fp);

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet