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;
    }
}
  • Possible duplicate of [Getting static property from a class with dynamic class name in PHP](http://stackoverflow.com/questions/1279081/getting-static-property-from-a-class-with-dynamic-class-name-in-php) – MatsLindh Feb 26 '17 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 –  Feb 26 '17 at 10:32

2 Answers2

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;
    }
}
Dorad
  • 3,413
  • 2
  • 44
  • 71
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.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84