Skip to content
Advertisement

Finding the PHP File (at run time) where a Class was Defined

Is there any reflection/introspection/magic in PHP that will let you find the PHP file where a particular class (or function) was defined?

In other words, I have the name of a PHP class, or an instantiated object. I want to pass this to something (function, Reflection class, etc.) that would return the file system path where the class was defined.

/path/to/class/definition.php

I realize I could use (get_included_files()) to get a list of all the files that have been included so far and then parse them all manually, but that’s a lot of file system access for a single attempt.

I also realize I could write some additional code in our __autoload mechanism that caches this information somewhere. However, modifying the existing __autoload is off limits in the situation I have in mind.

Hearing about extensions that can do this would be interesting, but I’d ultimately like something that can run on a “stock” install.

Advertisement

Answer

Try ReflectionClass

Example:

class Foo {}
$reflector = new ReflectionClass('Foo');
echo $reflector->getFileName();

This will return false when the filename cannot be found, e.g. on native classes.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement