如何在整个课堂上使变量成为全局变量 [英] How to make variable global across entire class

查看:79
本文介绍了如何在整个课堂上使变量成为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的问题,是否有可能使从类外部获取的变量全局成为整个类,这样我就不必在每个方法的开头都调用全局$ variable ?

Very simple question, is it possible to make a variable that is retrieved from outside of a class, 'global' to the whole class so that I do not have to call the 'global $variable' at the beginning of each method?

这是我目前正在做的事情:

class test{
    public function testing(){
        global $globalVariable,

        // Do something
    }
    public function testing_two(){
        global $globalVariable,

        // Do something
    }
}

换句话说,我可以将变量导入到构造函数中,从而使整个类都可以访问它们,而不必为每个方法调用全局吗?

更新

不知道我是否清楚我想实现。请参见以下内容:

Not sure if I have made it too clear with what I would like to achieve. Please see below:

$globalVariable = 'hello';

class test{
    public function testing(){
        global $globalVariable,

        // Do something
    }
    public function testing_two(){
        global $globalVariable,

        // Do something
    }
}


推荐答案

要清除操作方法:

您最多可能想做这样的事情
include('database.php'); 。那时,您包含的所有内容都是脚本的全局变量。现在,如果您具有上述类,则添加一个构造函数:

You most likely want to do something like this include('database.php');. At that very point everything you included there is global to your script. Now if you have a class like the above you add a constructor:

class testclass
{
    private $db;

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

    public function yourmethod()
    {
       $this->db->prepare(); // And so on
    }
}

让我们假设您的全局变量为在全局范围内称为$ db。您现在可以使用 new testclass($ db); 构造对象。现在,当您在所有方法中都使用 $ this-> db 时,则无需使用全局语句。

Let's assume your global variable is called $db in the global scope. You can just construct your object now using new testclass($db);. When you now use $this->db in all your methods there is no need to use the global statement.

这篇关于如何在整个课堂上使变量成为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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