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

PhpReflectionClass

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

For ReflectionClass in a namespaced file, add a prefix "" to make it global as following:

> $reflector = new \ReflectionClass('FOO');

Or else, it will generate an error said ReflectionClass in a namespace not defined. I didn't have rights to make comment for above answer, so I write this as a supplement answer.

Solution 3 - Php

Using a reflector you can build a function like this:

function file_by_function( $function_name ){
	if( function_exists( $function_name ) ){
		$reflector = new \ReflectionFunction( $function_name );
	}
	elseif( class_exists( $function_name ) ){
		$reflector = new \ReflectionClass( $function_name );
	}
	else{
		return false;
	}
	return $reflector->getFileName();
}

file_by_function( 'Foo' ) will return the file path where Foo is defined, both if Foo is a function or a class and false if it's not possible to find the file

Solution 4 - Php

if you had an includes folder, you could run a shell script command to "grep" for "class $className" by doing: $filename = ``grep -r "class $className" $includesFolder/*\ and it would return which file it was in. Other than that, i don't think there is any magic function for PHP to do it for ya.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlan StormView Question on Stackoverflow
Solution 1 - PhpGordonView Answer on Stackoverflow
Solution 2 - PhpJevinView Answer on Stackoverflow
Solution 3 - PhpJoseView Answer on Stackoverflow
Solution 4 - PhpSeauxView Answer on Stackoverflow