0
class KD_DB extends PDO {
    protected static $dbOne = '';
    protected static $dbTwo = '';

    public function setVariable ($alias,$content){
        switch($alias){
            case'one':  self::$dbOne = $content;  break;
            case'two':  self::$dbTwo = $content;  break;
        }
    }
}

Is there a way to create these dynamically?

Something like this to create the protected static variables

    public function setVariable ($alias,$content){
            self::${$alias} = $content;
    }

It did not work, but I suspect it is because I need it to be static to make it to work with a third class that extends this one...

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
ThomasK
  • 2,210
  • 3
  • 26
  • 35
  • Take a lool here: https://stackoverflow.com/questions/1279382/magic-get-getter-for-static-properties-in-php – colburton Dec 04 '19 at 19:00

1 Answers1

1

If you only have the two variables, it may be easier (with more appropriate names) to set them using a static function for each one, something like...

class KD_DB {
    public static $dbOne = '';
    public static $dbTwo = '';

    public static function setOne ($content){
        self::$dbOne = $content;
    }
}

KD_DB::setOne("value for one");

var_dump(KD_DB::$dbOne);

(code with minor changes to show the process)

But if you wanted a more open ended method, I would go for an associative array as the static variables and then use the 1 method (like you currently are) to set the value in the array...

class KD_DB {
    public static $data = [];

    public static function setVariable ($alias,$content){
        self::$data[$alias] = $content;
    }
}

KD_DB::setVariable("three", "value for three");

var_dump(KD_DB::$data);

this method can have issues if you mistype a variable reference which should be found during testing though, but does offer flexibility.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • I dont necessary only have two variables. It could be more, and it could be only one. A script containing a `foreach`-loop sets the `setVariable`-methood. – ThomasK Dec 04 '19 at 20:05
  • That is why I suggested the second method as an alternative. – Nigel Ren Dec 04 '19 at 20:12