Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is class instance in PHP?

The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.


Try ReflectionClass

  • ReflectionClass::getFileName — Gets a filename

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.


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.


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