我正在尝试编写一种可以在使用文件完整路径的扩展类中使用的方法。但是,当我使用 __FILE__
时,我只会返回定义继承方法的类的路径。这是一个示例:
foo.php
class foo
{
public function getFullFile()
{
return __FILE__;
}
}
酒吧.php
class bar extends foo
{
public function getFile()
{
return __FILE__;
}
}
例子.php
$foo = new foo();
echo $foo->getFullFile() . PHP_EOL;
$bar = new bar();
echo $bar->getFullFile() . PHP_EOL;
echo $bar->getFile() . PHP_EOL;
运行example.php的输出:
/my/full/path/foo.php
/my/full/path/foo.php
/my/full/path/bar.php
这是预期的行为吗?有没有更好的方法来完成这个?我在做一些愚蠢的事情吗?
最佳答案
您不能引用 __FILE__
(对于 said reasons ),但您可以引用当前对象类定义的文件:
class foo
{
public function getFullFile()
{
$c = new ReflectionClass($this);
return $c->getFileName();
}
}
关于PHP __FILE__ 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6985774/