0

I'm working on someone else's PHP code and my IDE (PHPstorm) is flagging this line with the error Cannot use [] for reading. The code works fine, but I'm trying to understand why with my limited PHP skills. I've seen double dollar signs in other files and with no error.

$somevar    = ($test_me) ? "some-class" : "some-other-class";
$$somevar[] = $some_value; // $somevar[] is flagged
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104
  • 2
    Variable variables are not a good way of programming. Use an array instead. – Andreas Sep 01 '20 at 08:31
  • 1
    This wouldn't have worked until PHP 7 - is there a chance you've got your IDE set up to validate against v5.X but are running it in 7+? – iainn Sep 01 '20 at 08:34
  • The answer to the dupe starting with "Overview" explains why this is legitimate in PHP7 but not PHP5 – Nick Sep 01 '20 at 08:41

2 Answers2

2

This is not the answer to your problem but what me and most other think you should do.
Switch to an array, that way you have one variable with everything that is variable in it.
You can loop the array to find what you need and you don't allocate variable names that may conflict with other variables.

$some_value =1;
$test_me = true;

$somevar    = ($test_me) ? "some-class" : "some-other-class";
$arr[$somevar] = $some_value;

var_dump($arr);

This results in an associative array with the key "some-class" and value 1.

Andreas
  • 23,610
  • 6
  • 30
  • 62
1

Use curly brackets { } for interpolation :

$somevar = "some-other-class";
${$somevar}[] = "foo";
var_dump(${$somevar});

Output :

array(1) {
  [0] => string(3) "foo"
}
Martijn
  • 15,791
  • 4
  • 36
  • 68
Cid
  • 14,968
  • 4
  • 30
  • 45