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;
.....
}
}
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.
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).
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With