开发者

PHP set current directory to class constant

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_开发者_StackOverflow社区_);
}

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).


Make it a static function that is initialized on first call:

class Conf {

 static protected $_root= null;

 static public function root() {
  if (is_null(self::$_root)) self::$_root= dirname(__FILE__);
  return self::$_root;
 }

}

This allows you to set root in-class and protects the value of root from overwrite.


You could use a static property instead of a constant like this:

Class Config {
    public static $ROOT = ''; // Can't call dirname yet
}
Config::$ROOT = dirname( __FILE__ ); // Now we can set it

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:

<?php
// classes/Config.php
eval('class Config { const ROOT = "'.dirname(__FILE__).'"; }');

It's very ugly but it worked for this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜