Alana Storm
Alana Storm

Reputation: 166046

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.

Upvotes: 140

Views: 79008

Answers (4)

Jose
Jose

Reputation: 322

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

Upvotes: 6

Gordon
Gordon

Reputation: 316959

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.

Upvotes: 274

Jevin
Jevin

Reputation: 109

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.

Upvotes: 11

Seaux
Seaux

Reputation: 3517

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.

Upvotes: 0

Related Questions