2

I have this static variable that I'm defining but I get an error in my code:

..unexpected '$_SERVER' (T_VARIABLE) in ...

class Constants {
        const ACCOUNTTYPE_SUPER_ADMIN   = 1;
        const ACCOUNTTYPE_COMPANY_ADMIN = 2;
        const ACCOUNTTYPE_AREA_ADMIN    = 3;
        const ACCOUNTTYPE_END_USER      = 4;

        const SAVETYPE_NEW              = 0;
        const SAVETYPE_EDIT             = 1;

        const LICENSE_VALIDITY_YEARS    = 1;
        const LICENSE_VALIDITY_LEFT_MAX = 12;

        public static $template_path = $_SERVER['DOCUMENT_ROOT'] . '/../_html/';
}
silkfire
  • 24,585
  • 15
  • 82
  • 105
  • It's not a static variable issue. It seems impossible to do this for *any* variable - probably for reasons similar to [Why don't PHP attributes allow functions?](http://stackoverflow.com/q/3960323) – Pekka Feb 22 '13 at 11:27
  • Set the value of a variable, you can only in method – Winston Feb 22 '13 at 11:30
  • Don't use static variables here, there's really no need to have it static.. – Andrew Feb 22 '13 at 11:33

3 Answers3

3

You cannot declare a static variable using a variable that way, but you can use a workaround for this:

class Constants {
    ...

    public static $template_path;
}

Constants::$template_path = $_SERVER['DOCUMENT_ROOT'] . '/../_html/';
Frhay
  • 424
  • 2
  • 16
  • Thanks a lot. Too bad you can't do it as I did, I mean I'm not using any functions or such? – silkfire Feb 22 '13 at 12:06
  • 1
    Glad to help... I faced the same problem and I had to work around it like I shown in my sample... not as clean as I would like, but it does the work... unfortunately PHP doesn't allow to declare with non-static values like we wish... :) – Frhay Feb 22 '13 at 13:09
2

You can only assign direct values when defining class members.

But you can create a method init() that would change your template path member value.

  public static function init(){ self::$template_path = $_SERVER['DOCUMENT_ROOT'] . '/../_html/'; }

and run it when you first use the class or instantiate it.

Glorious Kale
  • 1,273
  • 15
  • 25
0

you can use a static function

class Constants {
    // ...
    public static function getTemplatePath()
    {
        return $_SERVER['DOCUMENT_ROOT'] . '/../_html/';
    }
}

and can be used like

Constants::getTemplatePath();
ungalcrys
  • 5,242
  • 2
  • 39
  • 23