Getting the short name of a PHP class

Published on 2022-02-05 • Modified on 2022-02-05

In this snippet, we see how to get the short name of a PHP class. First with using reflection and secondarily using the Symfony string component. Note that even the first solution uses reflection; it's fast and should be faster than the second one, which I find more elegant.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use function Symfony\Component\String\u;

/**
 * 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 Snippet189Trait
{
    public function snippet189(): void
    {
        $article = new \App\Entity\Article();

        echo (new \ReflectionClass($article))->getShortName().PHP_EOL;

        echo u(\get_class($article))->afterLast('\\')->toString();

        // That's it! 😁
    }
}

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

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use PHPUnit\Framework\TestCase;

use function Symfony\Component\String\u;

/**
 * @see Snippet189Trait
 */
final class Snippet189Test extends TestCase
{
    /**
     * @see Snippet189Trait::snippet189
     */
    public function testSnippet189(): void
    {
        $article = new \App\Entity\Article();
        $withRefection = (new \ReflectionClass($article))->getShortName();
        $withSymfony = u(\get_class($article))->afterLast('\\')->toString();

        self::assertSame('Article', $withSymfony);
        self::assertSame($withRefection, $withSymfony);
    }
}