我正在尝试获取从超类继承的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();
}
}
Run Code Online (Sandbox Code Playgroud)
我不想覆盖的原因getAbsolutePathname()是会有很多类扩展AbstractFoo,在文件系统的许多不同的地方(Foo实际上是一个模块),它似乎违反了DRY.
好吧,你可以使用反射:
public function getAbsolutePathname() {
$reflector = new ReflectionObject($this);
return $reflector->getFilename();
}
Run Code Online (Sandbox Code Playgroud)
我不确定这是否会返回完整路径,或只是文件名,但我没有看到任何其他相关方法,所以试一试...
| 归档时间: |
|
| 查看次数: |
486 次 |
| 最近记录: |