Coder Perfect

Locating the PHP File in which a Class was Defined (at run time)

Problem

Is there any reflection/introspection/magic in PHP that will allow you to locate the PHP file that defines a specific class (or function)?

I have the name of a PHP class, or an instantiated object, in other words. I’d like to send this to a method (or a Reflection class) that returns the file system path where the class was defined.

/path/to/class/definition.php

I suppose I could acquire a list of all the files that have been included so far using (get included files()) and then manually parse them all, but that’s a lot of file system access for a single effort.

I also recognize that I could add some more code to our __autoload mechanism that caches this data. Modifying the existing __autoload, on the other hand, is not an option in the circumstance I’m considering.

It would be interesting to hear about extensions that can achieve this, but I’d like something that can operate on a “stock” setup.

Asked by Alan Storm

Solution #1

Try ReflectionClass

Example:

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

When the filename cannot be discovered, such as on native classes, this will return false.

Answered by Gordon

Solution #2

To make ReflectionClass global in a namespaced file, add the prefix “” like follows:

Otherwise, an error stating ReflectionClass in a namespace not declared would be generated. I didn’t have permission to add a remark on the previous response, so I’m writing this as a supplement.

Answered by Jevin

Solution #3

You can create a function like this with a reflector:

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();
}

If Foo is a function or a class, file by function(‘Foo’) will return the file path where Foo is declared, or false if the file cannot be found.

Answered by Jose

Solution #4

If you had an includes folder, you could use the shell script command $filename = “grep -r “class $className” $includesFolder/* to “grep” for “class $className.” It would then tell you which file it was in. Aside from that, I don’t believe there is a mystical PHP function that will do it for you.

Answered by Seaux

Post is based on https://stackoverflow.com/questions/2420066/finding-the-php-file-at-run-time-where-a-class-was-defined