Xhynk
Xhynk

Reputation: 13890

Proper use of Variable Scope in PHP

I've got a handful of variables that I need access to in more functions than I initially thought.

What would be the best way of including them in my growing list of functions?

I've got something like

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

I need almost all of those in a large handful of my functions. I was initially doing

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
}

That was great, until I realized I've got more functions to write than I initially thought.

What would be the best way to get all those variables into the scope of (almost) each function? Like I've done? Or something like using Constants? I'd like to avoid using session() if at all possible

Upvotes: 4

Views: 185

Answers (1)

Naftali
Naftali

Reputation: 146350

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

That way you do not pollute the global namespace and have the need to use the global keywords in every function.

For example:

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;
       //...
    }
}

Upvotes: 6

Related Questions