Proper use of variable scope in PHP

I have several variables for which I need access to more functions than I originally thought.

What would be the best way to include them in our growing list of features?

I have something like

$site = 'a'; $admin = 'b'; $dir = 'c'; $ma_plug = 'd'; $base = 'e'; //Etc. 

I need almost all of them in most of my functions. I originally did

 function a(){ global $site, $admin, $dir, $ma_plug, $base; //Write the A function } function b(){ global $site, $admin, $dir, $ma_plug, $base; //Write the B function } 

It was great until I realized that I have more writing features than I originally thought.

What would be the best way to get all of these variables into the scope of (almost) every function? How did i do this? Or something like using constants? I would like to avoid using session() , if at all possible

+4
source share
1 answer

If these functions are the only ones using these variables, it is better to make a class in which these variables are local.

Thus, you do not pollute the global namespace and should not use the global keywords in every function.

For instance:

 class MySite { private $site; private $admin; private $dir; private $ma_plug; private $base; function __construct($site, $admin, $dir, $ma, $base) { $this->site = $site; $this->admin = $admin; //... } } 
+6
source

All Articles