1

Today in a code audit, it was pointed out, that accessing a variable element like $array['keyname'] is not an optimum way to do it and instead a constant should be defined and then used as below.

define('KEYNAME', 'keyname'); // Constant defined somewhere centrally

$array[KEYNAME]; // actual usage

My question is, is that notion correct? And this is stemming from the tool Sonarqube.

enter image description here

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • 3
    I think the point of defining a constant here is to avoid hard-coded strings so in case your array keys change you only have to change the value in the defined constant instead of doing it for all the places that literal is used. – Rain Jan 16 '20 at 20:49
  • 1
    Principle of programming - DRY. You should follow it religiously. – Kapil Yadav Mar 31 '20 at 14:22

1 Answers1

3

If you were only accessing the array value by key once, then $array[‘key’] would be sufficient. But if you are accessing the value more than once, $array[self::CONSTANT] would keep your code DRYish.

If the key were dynamic, then obviously a constant wouldn’t be appropriate. Instead, using a property would have the same result. I.e. $array[$this->property]

Jesse Rushlow
  • 196
  • 1
  • 7