Récupérer le chemin d'une interface ou classe PHP

Publié le 08/08/2023 • Actualisé le 08/08/2023


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous voyons comment récupérer le chemin d'une interface ou classe PHP. C'est parfois utilise quand on veut déboguer des problèmes d'autoloading.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Helper\String\AppStringInterface;

use function Symfony\Component\String\u;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 */
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! 😁
    }
}

 Exécuter le snippet  Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !