How to pass Global variables to classes in PHP?

18,512

Solution 1

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...

Solution 2

Generally, PHP provides $GLOBAL array, which can be used to access superglobal variables. BTW, using this array is not much better than using "global" statement in the beginning of all your methods. Also, using such approach does not seem to be a good practice for object-oriented code.

So, you can:

  • either pass these variables as constructor parameter (see answer from ircmaxell for details)

  • or use some configuration class (singleton)

Decision depends on semantics of your global parameters.

Solution 3

Try passing the variable that you want to be global to the object as an argument, and then use the __constructor() method to make it a class property.

You can find more info and examples here: In php when initializing a class how would one pass a variable to that class to be used in its functions?

Solution 4

Copy them into object variables in the constructor.

 global $user;
 $this->user = $user;

It's not too elegant, anyway, using globals is not too elegant.

Share:
18,512
Waseem Senjer
Author by

Waseem Senjer

Updated on June 09, 2022

Comments

  • Waseem Senjer
    Waseem Senjer almost 2 years

    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;
    
        .....
    }
    
    } 
    
  • Waseem Senjer
    Waseem Senjer over 13 years
    can I pass an Object as a parameter in the constructor ?