tags:

views:

178

answers:

2

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

A: 

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
Doug Neiner
+2  A: 

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.

pygorex1
Even though I went with a completely different solution, I like it.
Corey Hart