Search code examples
phpvariablesstatic-variables

php initialize static variable with other static variable


I tried to initialize a static var with the content of another one and it seems to fail.

class Hey {
    static $user = "peter";
    static $home = '/home'.Hey::$user;

    // syntax error, unexpected T_VARIABLE, expecting T_STRING

Why does it fail and is there a way without an init-function or something else?


Solution

  • class Hey {
        static $user = "peter";
        static $home;
    }
    Hey::$home =  '/home'.Hey::$user;
    

    or if $home is private:

    class Hey {
        static $user = "peter";
        private static $home;
        static function init(){self::$home = '/home'.self::$user;}
    }
    Hey::init();
    

    see How to initialize static variables