PHP 7.1: Get file path from namespace

Viewed 6401

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?

2 Answers

You could use the __NAMESPACE__ global and then replace the backslash with the proper directory separator, then use the __FILE__ global to append the filename

$ns = str_replace( __NAMESPACE__, DIRECTORY_SEPARATOR, '\\' );
$path = $ns.DIRECTORY_SEPARATOR.__FILE__;

and then do what you want with it.

Related