Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 7.1: Get file path from namespace

Tags:

php

php-7.1

I have a project. I need to get the contents of a file in a package. I could do it the hard way:

file_get_contents('../../vendor/{vendor}/{package}/src/
    {directory}/{sub-directory}/class.php');

Or, I could do it the "easy way," which I'm pretty sure is impossible.

namespace MyVendor\MyProject;

use TheirVendor\TheirPackage\TheirClass;

class MyObject
{
    public function myFunction()
    {
        return file_get_contents(TheirClass);
    }
}

Is this (or something like it) possible?

like image 616
Josh Bruce Avatar asked Oct 04 '17 00:10

Josh Bruce


1 Answers

You can get the file name of where a class is declared using a ReflectionClass instance and its getFileName() method:

$reflector = new ReflectionClass(\Vendor\Package\Class::class);
echo $reflector->getFileName();
like image 92
Marty Avatar answered Nov 04 '22 11:11

Marty