0

Is it possible to be able to dynamically set a php static class variable? In the example below i want to pass a string representation of the variable i want to set to a function "databaseInit" which then sets the var...

class app {
    static $database_smf;
    static $database_phpbb;

    /**
     * Initialise the app
     */
    static function init(){

        // No initialise the db connection
        self::databaseInit('database_phpbb');
        self::databaseInit('database_smf');

    }

    static function databaseInit( $database ){
        // is it possible to dynamically set the static var based on the param provided? eg:
        self::[$database] = true;
    }
}
2
  • Possible duplicate of Getting static property from a class with dynamic class name in PHP Commented Feb 26, 2017 at 10:22
  • The question you linked is not straight forward and neither are the answers. So, technically yes, but i would say this question will assist others getting to the bottom of the issue with much more efficiency :D Commented Feb 26, 2017 at 10:32

2 Answers 2

0

You can use a plain variable variable name:

static function databaseInit( $database ){
    self::$$database = true;
}

.. but you should really rework it to just keep an array and manipulate the keys of the array instead, as that will keep all the settings inside a single namespace instead of potentially doing weird stuff with other static variables if a name is mistyped, etc.

class app {
    static $databases = [];

    ...

    static function databaseInit($database) {
        self::$databases[$database] = true;
    }
}

And the next step would be to make the class non-static instead, so it can be easier tested and will keep its state locally instead.

Sign up to request clarification or add additional context in comments.

1 Comment

ah of course yes! variable variable! Perfect thanks!
0

Yes that is possible. Just a little change in your code:

Use:

self::$$database = true;

Instead of:

self::[$database] = true;

class app {
    static $database_smf;
    static $database_phpbb;

Full code:

    /**
     * Initialise the app
     */
    static function init(){

        // No initialise the db connection
        self::databaseInit('database_phpbb');
        self::databaseInit('database_smf');

    }

    static function databaseInit( $database ){
        // is it possible to dynamically set the static var based on the param provided? eg:
        self::$$database = true;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.