Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP __FILE__ inheritence

I am trying to write a method that I can use in extended classes that uses the file's full path. However, when I use __FILE__ I only get back the path for the class the inherited method is defined in. Here is an example:

foo.php

class foo 
{

    public function getFullFile()
    {
        return __FILE__;
    }
}

bar.php

class bar extends foo 
{
    public function getFile()
    {
        return __FILE__;
    }

}

example.php

$foo = new foo();
echo $foo->getFullFile() . PHP_EOL;

$bar = new bar();
echo $bar->getFullFile() . PHP_EOL;
echo $bar->getFile() . PHP_EOL;

The output of running example.php:

/my/full/path/foo.php
/my/full/path/foo.php
/my/full/path/bar.php

Is this expected behavior? Is there a better way to accomplish this? Am I doing something insanely stupid?

like image 618
dmcnelis Avatar asked Jan 26 '26 06:01

dmcnelis


1 Answers

You can not refer to __FILE__ (for said reasons), but you can refer to the file the current object's class has been defined in:

class foo 
{
    public function getFullFile()
    {
        $c = new ReflectionClass($this);
        return $c->getFileName();
    }
}
like image 94
hakre Avatar answered Jan 27 '26 22:01

hakre