题
我试图让一个PHP类的绝对路径从一个超类继承。现在看来似乎应该是简单的。我认为下面的代码为简洁地解释它尽可能:
// 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();
}
}
我之所以不想覆盖getAbsolutePathname()
是,有将是一个很大的扩展AbstractFoo,在潜在的许多不同的地方上的文件系统(美孚实际上是一个模块)类和它似乎是一个违反DRY。
解决方案
那么,你可以使用反射:
public function getAbsolutePathname() {
$reflector = new ReflectionObject($this);
return $reflector->getFilename();
}
我不知道是否会返回的完整路径,或者只是文件名,但我没有看到任何其他相关方法,所以给它一个尝试...
其他提示
据我所知,没有此没有干净的解决方法。魔术常量__FILE__
和__DIR__
正在分析中解释,而不是动态的。
我倾向于做的是
class AbstractFoo {
protected $path = null;
public function getAbsolutePathname() {
if ($this->path == null)
die ("You forgot to define a path in ".get_class($this));
return $this->path;
}
}
class Foo extends AbstractFoo {
protected $path = __DIR__;
}
您可以砍的东西了debug_backtrace
,但仍然需要你明确地覆盖父函数中的每个子类中。
这是更容易来定义函数在每个子类return __FILE__;
。 __FILE__
将始终与在它被发现的文件名代替,有没有办法让它否则做。
不隶属于 StackOverflow