如何将全局变量传递给PHP中的类? [英] How to pass Global variables to classes in PHP?

查看:125
本文介绍了如何将全局变量传递给PHP中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将全局变量传递给我想使用的类,而无需在类的每个方法中声明它们为全局变量?



示例:

  $ admin =admin_area; 

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

管理员我希望变量$ admin可以在所有方法中访问没有这样做的类:

  class Administrator {

public function auth($ pass,$ user ){

global $ admin;
.....

}
public function logout(){
global $ admin;

.....
}

}


<您可以声明一个成员变量,并将其传递给构造函数:

 

class Administrator {
protected $ admin ='';

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


public function logout(){
$ this-> admin; //这就是你如何访问它


$ / code>

然后通过以下方式实例化:

  $ adminObject = new Administrator($ admin); 

但我建议尽量避免使用全局变量。他们会让你的代码更难以阅读和调试。通过做类似上面的事情(将它传递给类的构造函数),可以大大改善它...


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;

    .....
}

} 

解决方案

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

这篇关于如何将全局变量传递给PHP中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆