Search code examples
phppropertiesstaticconstantsprivate

PHP: Cannot set a value for a private static property


I have a very simple issue where I am trying to set a private static property value made up of a constant appended with some text like this:

private static $cssDirectory = APP_ROOT.'css/';

I am getting a syntax error. I can fix this by making the private variable not static and assign a value with a constructor for example but since I want it static I am curious what can I do about it. I can also make a constant for the whole value and use that but again I am curious why I can't do it like I tried. Maybe I am doing something wrong also. Thanks.


Solution

  • From the PHP docs

    Class member variables are called "properties"... They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value --that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

    Concatenation is a run-time operation.

    You don't need to instantiate and set the property value in the constructor.... you can write a static setter method instead

    Note also that PHP 5.6 does allow this type of initialization of class properties

    EDIT

    Example of a static setter method:

    private static $cssDirectory;
    
    public static setCssDirectory() {
        self::$cssDirectory = APP_ROOT.'css/';
    }
    

    And then you just call

    myClassName::setCssDirectory();
    

    before anything else