Search code examples
phpvariable-variablesstatic-array

Assign value to variable private static class property that is an array from inside class definition


I would like to access and assign values to private static class properties and I would like to do the assigning using the concept of 'variable variables'. Accessing works, but assigning does not work. I have tried the following:

class AClass {
    private static $testArray = array();

    public static function aFunction() {
        $key = 'something';
        $arrayName = 'testArray';
        $array = self::$$arrayName;
        // accessing:
        $value = $array[$key]; // This works, $value holds what self::testArray['something'] holds.


        // assigning:
        // version 1:
        $array[$key] = $value; // No error, but self::testArray['something'] does not get updated

        // version 2:
        self::$$arrayName[$key] = $value; // Error
    }
}

Also: I had some trouble coming up with a precise and concise title. If you feel like you understand my problem and can think of a better title, pleas suggest it!


Solution

  • For the version 1,

    Your array may be a copy of the static array, so assignment will be only on local copy. Since PHP 5, object are passed by reference, by default, but I think array still be passed by copy (except if you specific reference with &) - not 100% sure about that point

    For the version 2,

    You should try self::${$arrayName}[$key]

    There is a priority order problem, you want the PHP to evaluate your "var's var" before interpreting the []. Without the {}, PHP is trying to evaluate something like

    self::${$arrayName[$key]}
    

    instead of

    self::${$arrayName}[$key]