忘记后期静态绑定,我需要后期静态 __FILE__
我正在寻找 __FILE__
的 get_used_class()
等效项...也许类似于 get_included_file()
?
我有一组类想知道它们存在于哪个目录中。像这样:
<?php
class A {
protected $baseDir;
public function __construct() {
$this->baseDir = dirname(__FILE__);
}
public function getBaseDir() {
return $this->baseDir;
}
}
?>
在其他文件中,在其他文件夹中...
<?php
class B extends A {
// ...
}
class C extends B {
// ...
}
$a = new A;
echo $a->getBaseDir();
$b = new B;
echo $b->getBaseDir();
$c = new C;
echo $c->getBaseDir();
// Annnd... all three return the same base directory.
?>
现在,我可以做一些贫民窟的事情,比如添加 $this- >baseDir = dirname(__FILE__)
对于每个扩展类,但这似乎有点……贫民窟。毕竟,我们谈论的是 PHP 5.3,对吧?这不应该是未来吗?
是否有另一种方法来获取声明类的文件的路径?
I'm looking for the get_called_class()
equivalent for __FILE__
... Maybe something like get_included_file()
?
I have a set of classes which would like to know what directory they exist in. Something like this:
<?php
class A {
protected $baseDir;
public function __construct() {
$this->baseDir = dirname(__FILE__);
}
public function getBaseDir() {
return $this->baseDir;
}
}
?>
And in some other file, in some other folder...
<?php
class B extends A {
// ...
}
class C extends B {
// ...
}
$a = new A;
echo $a->getBaseDir();
$b = new B;
echo $b->getBaseDir();
$c = new C;
echo $c->getBaseDir();
// Annnd... all three return the same base directory.
?>
Now, I could do something ghetto, like adding $this->baseDir = dirname(__FILE__)
to each and every extending class, but that seems a bit... ghetto. After all, we're talking about PHP 5.3, right? Isn't this supposed to be the future?
Is there another way to get the path to the file where a class was declared?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
ReflectionClass::getFileName
ReflectionClass::getFileName
您是否尝试过将其分配为类的静态成员?
(未经测试,静态加上类继承变得非常有趣......)
Have you tried assigning it as a static member of the class?
(Untested, and statics plus class inheritance becomes very fun...)
如果您不使用
__FILE__
而是使用单独的变量并将变量设置为__FILE__
在每个类中,您仍然需要在每个类中重新声明属性,而不是方法
what if you don't use
__FILE__
but a separate variable and set the variable to__FILE__
in each classyou still have to redeclare the property in each class, but not the method
您可以使用 debug_backtrace()。但你可能不想这样做。
You could use debug_backtrace(). You probably don't want to, though.
经测试:
不起作用。
看起来该常量是在类加载时注册的,而不是“迟到”。
不确定以前是否可行,但今天对我来说最好的是使用反射:
Tested:
Doesn't work.
It looks like the constant is registered when the class is loaded which is not "late".
Not sure it was possible before, but what was best for me today is using reflection :