如何从继承的方法获取派生类的路径? [英] How to get the path of a derived class from an inherited method?
问题描述
如何从继承的方法获取当前类的路径?
我有以下内容:
<?php // file: /parentDir/class.php
class Parent {
protected function getDir() {
return dirname(__FILE__);
}
}
?>
和
<?php // file: /childDir/class.php
class Child extends Parent {
public function __construct() {
echo $this->getDir();
}
}
$tmp = new Child(); // output: '/parentDir'
?>
__ FILE __
常量始终指向源 - 它所在的文件的文件,无论继承。
我想得到派生类的路径名称。
The __FILE__
constant always points to the source-file of the file it is in, regardless of inheritance.
I would like to get the name of the path for the derived class.
有没有优雅的方式吗?
Is there any elegant way of doing this?
我可以按照<$ c $的方式做点什么c> $ this-> getDir(__ FILE __); 但这意味着我必须经常重复自己。我正在寻找一种方法,如果可能的话,将所有逻辑放在父类中。
I could do something along the lines of $this->getDir(__FILE__);
but that would mean that I have to repeat myself quite often. I'm looking for a method that puts all the logic in the parent class, if possible.
更新:
接受的解决方案( Palantir ):
<?php // file: /parentDir/class.php
class Parent {
protected function getDir() {
$reflector = new ReflectionClass(get_class($this));
return dirname($reflector->getFileName());
}
}
?>
推荐答案
使用 ReflectionClass :: getFileName
这个会得到你的dirname class 定义了孩子
。
$reflector = new ReflectionClass("Child");
$fn = $reflector->getFileName();
return dirname($fn);
您可以使用 get_class()
:)
You can get the class name of an object with get_class()
:)
这篇关于如何从继承的方法获取派生类的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!