views:

35

answers:

2

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.

+5  A: 

Try

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.

Gordon
Perfect, exactly what I was looking for (but was too lazy to glop through the Reflection API docs myself)
Alan Storm
+1  A: 

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.

ocdcoder
wow, i completely missed @Gordon's answer, heh...much better than mine...
ocdcoder
Honest, non-asshole curiosity here. What made you think this answer was any better than the idea I'd already considered and rejected? "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."
Alan Storm
because its one line as opposed to however many lines it'd take to write a parser in PHP and the grep function is compiled C, i think, and likely much faster than whatever would have been written.
ocdcoder
Ah, got it. My actual concern was repeated disk access to each of the files over and over again to do this (it's something that will happen a lot in the tool I'm building) and not the amount of code I'll try to make that clearer next time. (FYI: You should look into ack. It's way better than grep!)
Alan Storm
ack or awk? I love awk, its actually my fav programming language, but more people use grep regularly...its "cleaner" for stuff this simple
ocdcoder
Not awk, ack: http://betterthangrep.com/ It's perl back grep replacement that's optimized for search code based projects. It's great.
Alan Storm