PHP 将当前目录设置为类常量
我的项目的根目录中有一个配置文件,其中包含一类特定于环境的常量。我遇到的问题是如何将当前目录设置为 ROOT var。其效果是:
Class Config {
const ROOT = dirname(__FILE__);
}
这是不可能的,因为它是一个常量表达式。我还尝试过在每个实例的交易上更改它,例如:
Class Config {
const ROOT = '/old/path';
public function __construct(){ $this->ROOT = '/new/path'; echo $this->ROOT; }
}
$config = new Config;
这似乎可行,但这需要在我的所有类之间传递 $config 。有没有人找到解决这个问题的方法?
(另外,我还没有使用 php5.3,所以 __DIR__ 不起作用)。
I have a config file at the root directory of my project which contains a class of constants that are environment specific. The problem I'm having is how to set the current directory as the ROOT var. Something to the effect of:
Class Config {
const ROOT = dirname(__FILE__);
}
This isn't possible as it is a constant expression. I've also tried changing it on a per instance deal like:
Class Config {
const ROOT = '/old/path';
public function __construct(){ $this->ROOT = '/new/path'; echo $this->ROOT; }
}
$config = new Config;
This seems to work, but this requires passing around $config between all my classes. Has anyone found a hack around this?
(Also, I'm not on php5.3 yet, so __DIR__
won't work).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使其成为在第一次调用时初始化的静态函数:
这允许您在类中设置 root 并保护 root 的值不被覆盖。
Make it a static function that is initialized on first call:
This allows you to set root in-class and protects the value of root from overwrite.
您可以使用
static
属性而不是这样的常量:然后您可以在任何地方调用它(假设包含您的配置文件),如下所示:
You could use a
static
property instead of a constant like this:And then you can call it anywhere (assuming your config file is included) like this:
我正在挖掘这个问题,因为我在另一个项目中找到了另一个解决方案。
该项目已经使用了该常量,因此我无法更改对 Config::ROOT 常量的所有调用。
解决方案是这样的:
它非常丑陋,但它适用于这种情况。
I'm digging up this issue because I found another solution in another project.
The project already used the constant so I could not change all calls to the
Config::ROOT
constant.The solution was this one:
It's very ugly but it worked for this case.