-5

I am learning MVC based web pages in php.I have few php files with multiple classes & methods in MVC layers.I have many variables & large arrays that need to be accessed in several files.some sample given below:

$label = array("lng"=>Language",tlabel"=>"Title", 
               "content"=>"Details", "tm"=>"Date", 
               "authr"=>"Post By");
$route_url;
$database;
$navbar_text;
$footer_text;

I saw few php example about using php keyword global. But using it in many parts of the code will become very messy to keep track.I also saw another technique where every common things goes inside a special class called Config like given below:

// does it need auto load? i don't know
class Config
{

    public static $label = array("lng"=>Language","tlabel"=>"Title", 
                                   "content"=>"Details", "tm"=>"Date", 
                                   "authr"=>"Post By");
    public static $route_url;
    public static $database;
    public static $navbar_text;
    public static $footer_text;

}

echo SmtpConfig::$label["tlabel"];

So, please suggest the correct way in which MVC web developer do such things.Thanks

user5005768Himadree
  • 1,375
  • 3
  • 23
  • 61
  • 1
    Cluttering up the global scope is considered bad practice, you might want to check out [Dependency Injection](https://stackoverflow.com/questions/130794/what-is-dependency-injection) instead. – CD001 Jul 24 '18 at 08:15
  • 2
    That is not a good idea, it destroys the encapsulation of a class/object. Instead pass the data into the class as a parameter. Of the constructor if possible and save it as a property. Or as a parameter to a method if it is only required by that method – RiggsFolly Jul 24 '18 at 08:15
  • 1
    If you find it hard to keep track of them when using the `global` keyword, imagine how much harder it'd be to keep track without it. – user3942918 Jul 24 '18 at 08:17
  • Don't call variable is coming from outside class and called from inside class, you can use a parameter in the function – Rendi Wahyudi Muliawan Jul 24 '18 at 08:19
  • 2
    Hands off from globals... use OOP properly – B001ᛦ Jul 24 '18 at 08:35
  • 1
    You can't. That's how the language is designed. The fact that you're using so many globals, however, should be a big red flag that there's something fundementally wrong with your design. https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil – GordonM Jul 24 '18 at 08:59

2 Answers2

2

You can use Static Class Variables.

The second approach to use $GLOBAL vars.

But it is not a good approach to use a lot of global variables.

azizsagi
  • 268
  • 3
  • 12
1

You can do that using $GLOBALS super global array which is accessible throughout whole PHP script.

Add your variables in $GLOBALS super global array like,

$GLOBALS['data'] = 'Something'; 

and now you can access this variable globally like,

$something = $GLOBALS['data']
Harsh Virani
  • 367
  • 3
  • 8