Php 获取扩展类的文件名
假设我有两个文件,每个文件都有一个类。如何在父类中获取子类所在的文件名 文件2(子类): 文件1:Php 获取扩展类的文件名,php,class,Php,Class,假设我有两个文件,每个文件都有一个类。如何在父类中获取子类所在的文件名 文件2(子类): 文件1: class A{ final protected function __construct(){ // here I want to get the filename where class B is, // or whatever class is the child } } 我不确定它有什么作用,但你可以这样说: class A{ final protec
class A{
final protected function __construct(){
// here I want to get the filename where class B is,
// or whatever class is the child
}
}
我不确定它有什么作用,但你可以这样说:
class A{
final protected function __construct(){
$obj = new ReflectionClass($this);
$filename = $obj->getFileName();
}
}
你可以作弊并使用:
这不是正确的选择吗?您应该将构造函数的可访问性更改为
public
@webbiedave很难说OP是如何使用受保护的构造函数创建对象的,但它们可能有其原因。也许他们在a
上有一个公共的静态工厂方法,Phil,我刚刚备份了你对OP问题的原始评论,现在你欺骗了我!)你想让父类在构建时以某种方式神奇地知道单个任意子类的位置吗?这是不容易做到的,也没有任何目的。你到底想干什么?可能有更好的方法来实现您的实际最终目标。如何使用受保护的构造函数实例化类?
class A{
final protected function __construct(){
$obj = new ReflectionClass($this);
$filename = $obj->getFileName();
}
}
class A {
final protected function __construct() {
$stacktrace = @debug_backtrace(false);
$filename = $stacktrace[0]['file'];
}
}