如何避免使用PHP全局对象? [英] How to avoid using PHP global objects?

查看:84
本文介绍了如何避免使用PHP全局对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在创建博客系统,希望将来可以将其变成一个完整的CMS.

I'm currently creating blog system, which I hope to turn into a full CMS in the future.

有两个对全局访问有用的类/对象(mysqli数据库连接和一个检查用户是否已登录的自定义类).

There are two classes/objects that would be useful to have global access to (the mysqli database connection and a custom class which checks whether a user is logged in).

我正在寻找一种不使用全局对象的方法,并且尽可能避免每次调用对象时都将其传递给每个函数.

I am looking for a way to do this without using global objects, and if possible, not passing the objects to each function every time they are called.

推荐答案

您可以将对象设置为静态,然后可以在任何地方访问它们.示例:

You could make the objects Static, then you have access to them anywhere. Example:

myClass::myFunction();

这将在脚本中的任何地方起作用.但是,您可能需要阅读静态类,并可能使用Singleton类在可以在任何地方使用的静态对象内部创建常规类.

That will work anywhere in the script. You might want to read up on static classes however, and possibly using a Singleton class to create a regular class inside of a static object that can be used anywhere.

扩展

我认为您要尝试的工作与我对数据库类所做的工作非常相似.

I think what you are trying to do is very similar to what I do with my DB class.

class myClass
{
    static $class = false;
    static function get_connection()
    {
        if(self::$class == false)
        {
            self::$class = new myClass;
        }
        return self::$class;
    }
    // Then create regular class functions.
}

发生的事情是,在使用$ object = myClass :: get_connection()获得连接后,您将能够定期执行任何功能.

What happens is after you get the connection, using $object = myClass::get_connection(), you will be able to do anything function regularly.

$object = myClass::get_connection();
$object->runClass();

扩展

执行了静态声明后,只需调用get_connection并将返回值分配给变量即可.然后,其余函数可以具有与您通过$ class = new myClass调用的类相同的行为(因为这就是我们所做的).您要做的就是将class变量存储在静态类中.

Once you do that static declarations, you just have to call get_connection and assign the return value to a variable. Then the rest of the functions can have the same behavior as a class you called with $class = new myClass (because that is what we did). All you are doing is storing the class variable inside a static class.

class myClass
{
    static $class = false;
    static function get_connection()
    {
        if(self::$class == false)
        {
            self::$class = new myClass;
        }
        return self::$class;
    }
    // Then create regular class functions.
    public function is_logged_in()
    {
        // This will work
        $this->test = "Hi";
        echo $this->test;
    }
}

$object = myClass::get_connection();
$object->is_logged_in();

这篇关于如何避免使用PHP全局对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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