Skip to content

Instantly share code, notes, and snippets.

@ManojKiranA
Forked from joemaller/child-filepath.md
Created June 17, 2022 15:06
Show Gist options
  • Save ManojKiranA/f5ce8b453774cbda15a5b0e665f3bd4f to your computer and use it in GitHub Desktop.
Save ManojKiranA/f5ce8b453774cbda15a5b0e665f3bd4f 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.

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