PHP 8.1: getting the FQCN of a variable with ::class

Published on 2022-09-11 • Modified on 2022-09-11

This snippet shows how to get the FQCN of a variable with ::class; this is new functionality introduced in PHP 8.1. Before, we could only use :class on a class. Now, we can do it on a variable, which is more elegant than using the get_class() function. Check all snippets about the new PHP 8.1 functionalities here.


<?php

declare(strict_types=1);

// src/Controller/Snippet/Snippet219Trait.php

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

/**
 * 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 Snippet219Trait
{
    public function snippet219(Request $request): void
    {
        echo 'Class with ::class ='.$request::class.PHP_EOL;

        echo 'Class with get_class() ='.\get_class($request);

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow  Random snippet

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;

/**
 * @see Snippet219Trait
 */
final class Snippet219Test extends TestCase
{
    /**
     * @see Snippet219Trait::snippet219
     */
    public function testSnippet219(): void
    {
        $request = new Request();

        self::assertSame($request::class, \get_class($request));
    }
}