Search code examples
phppathname

Getting the pathname of an inherited class in PHP


I'm trying to get the absolute pathname of a PHP class that inherits from a superclass. It seems like it should be simple. I think the code below explains it as succinctly as possible:

// myapp/classes/foo/bar/AbstractFoo.php
class AbstractFoo {

    public function getAbsolutePathname() {
        // this always returns the pathname of AbstractFoo.php
        return __FILE__;
    }

}


// myapp/classes/Foo.php
class Foo extends AbstractFoo {

    public function test() {
        // this returns the pathname of AbstractFoo.php, when what I
        // want is the pathname of Foo.php - WITHOUT having to override
        // getAbsolutePathname()
        return $this->getAbsolutePathname();
    }

}

The reason I don't want to override getAbsolutePathname() is that there are going to be a lot of classes that extend AbstractFoo, in potentially many different places on the filesystem (Foo is actually a module) and it seems like a violation of DRY.


Solution

  • Well, you could use reflection:

    public function getAbsolutePathname() {
        $reflector = new ReflectionObject($this);
        return $reflector->getFilename();
    }
    

    I'm not sure if that will return the full path, or just the filename, but I don't see any other relevant methods, so give it a try...