Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Global variables to classes in PHP?

How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

$admin = "admin_area";

if($_POST['login']){
      $user = new Administrator;
      $user->auth($pass,$username);
    }

in the class Administrator I want the variable $admin be accessible in all methods of the class without doing this :

class Administrator{

   public function auth($pass,$user){

     global $admin;
     .....

  }
  public function logout(){
    global $admin;

    .....
}

} 
like image 658
Waseem Senjer Avatar asked Jan 22 '11 13:01

Waseem Senjer


People also ask

How can access global variable in PHP class?

Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.

Can global variables be used in classes?

A global variable is a visible variable and can be used in every part of a program. Global variables are also not defined within any function or method. On the other hand, local variables are defined within functions and can only be used within those function(s).

Can global variables be accessed outside the class?

If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.

Why not use global variables PHP?

That's because variables aren't really global in PHP. The scope of a typical PHP program is one HTTP request. Session variables actually have a wider scope than PHP "global" variables because they typically encompass many HTTP requests.


1 Answers

Well, you can declare a member variable, and pass it to the constructor:

class Administrator {
    protected $admin = '';

    public function __construct($admin) {
        $this->admin = $admin;
    }

    public function logout() {
        $this->admin; //That's how you access it
    }
}

Then instantiate by:

$adminObject = new Administrator($admin);

But I'd suggest trying to avoid the global variables as much as possible. They will make your code much harder to read and debug. By doing something like above (passing it to the constructor of a class), you improve it greatly...

like image 155
ircmaxell Avatar answered Sep 22 '22 03:09

ircmaxell