0

It is a good or a bad practice to call global variables inside class methods? Yes/No and why? Check the following example:

PHP file that contains the global variable:

 $a = ['a1','a2','a3','a4','a5'];

Class method:

 private function foo($i)
 {
  global $a;
  return $a[$i];
 }
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119

2 Answers2

0

You should really be keeping variables in local scopes and pass them as values or references. From what I learnt in Java and C, these variables would take up space (RAM) and you could run into a mistake of modifying a variables from another class when you weren't meant too.

lecardo
  • 1,208
  • 4
  • 15
  • 37
0

global variables are accessible from any part of the program and thus can be modified, for example if you want to import a library for your project and turns out that that library is using a variable with the same name your program will stop working and generate errors you will find difficult to solve. another problem with global variables is that when your project grows larger you might use a variable name you already used before.

jrod
  • 66
  • 1
  • 6