Skip to content

Instantly share code, notes, and snippets.

@joemaller
Last active June 17, 2022 15:13
Show Gist options
  • Save joemaller/f8edb03408f7ffe878700e1bb129a5b3 to your computer and use it in GitHub Desktop.
Save joemaller/f8edb03408f7ffe878700e1bb129a5b3 to your computer and use it in GitHub Desktop.
Get PHP child Class file paths from inherited parent class methods

Get PHP child Class file paths from inherited parent class methods

While refactoring some code into a reusable PHP Class I hit a brief roadblock where some code expected the __FILE__ magic constant file path. Since that value always refers to the specific file it's called from, it won't work from a separate Class file because the referenced path would be the parent instead of the child.

The full filepath of a child Class can be inferred from an inherited parent Class method by combining get_class($this) or get_called_class() with the ReflectionClass::getFileName method like this:

// ParentClass.php
class ParentClass
{
    public function __construct()
    {
      $childRef = new \ReflectionClass(get_class($this));
        echo __FILE__;
        echo "\n";
        echo $childRef->getFileName();
    }
}

// ChildClass.php
class ChildClass extends ParentClass
{
}

// index.php
require 'ParentClass.php';
require 'ChildClass.php';

new ChildClass();

Output:

/var/www/html/ParentClass.php
/var/www/html/ChildClass.php

For some reason, this was difficult to search for, but eventually I found this ancient Stack Overflow answer which got me most of the way there.

@nowinskp
Copy link

Thank you for this gist, it was very helpful!

@ManojKiranA
Copy link

thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment