Getting the path of a PHP interface or class

Published on 2023-08-08 • Modified on 2023-08-08

This snippet shows how to get the path of a PHP interface or class. It can sometimes be helpful when debugging autoloading issues.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Helper\String\AppStringInterface;

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 Snippet266Trait
{
    public function snippet266(): void
    {
        $reflector = new \ReflectionClass(AppStringInterface::class);
        $fileName = $reflector->getFileName();
        echo sprintf('The physical path of the %s interface is %s.', AppStringInterface::class, u((string) $fileName)->split('strangebuzz.com')[1] ?? '');

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!