简体   繁体   English

如何在 PHP 的另一个 class 中使用 class 的实例

[英]How to use an instance of a class within another class in PHP 7

I have what seems like a simple query but I have not found an answer elsewhere.我有一个看似简单的查询,但我在其他地方没有找到答案。 I have 2 classes, one called DB which essentially connects to the database and can then run queries.我有 2 个类,一个称为 DB,它本质上连接到数据库,然后可以运行查询。 I instantiate it at the top of the document $db= new DB;我在文档顶部实例化它 $db= new DB; and I can then run a series of queries on the database throughout the page.然后我可以在整个页面中对数据库运行一系列查询。 The issue I am having is that I want to use this instance within another class I have called User.我遇到的问题是我想在另一个 class 中使用这个实例,我已经调用了 User。 I know I can either instantiate again but this does not make sense OR pass the instance of DB when instantiating User, for instance $user = new User($db);我知道我可以再次实例化,但这没有意义,或者在实例化用户时传递数据库实例,例如 $user = new User($db); but considering the $db instance will be used by most classes I am going to create I am thinking there is a better solution to import it into other classes.但考虑到 $db 实例将被我要创建的大多数类使用,我认为有一个更好的解决方案可以将它导入其他类。 I have looked at the global route but I read it is bad practice + I am getting unexpected global error我查看了全球路线,但我读到这是不好的做法 + 我遇到了意外的全球错误

class User{
    global $db;

    public function __construct()
    {
        var_dump($this-> db);
    }//end constructor
}//end class

Since your DB client will be instantiated once and then used everywhere else my initial thought was to recommend passing it as a constructor parameter (dependency injection), but since you are not fan of this approach, I would recommend making your DB client a singleton class, which means it can only be instantiated once and any subsequent attempt would return the same instance everywhere.由于您的数据库客户端将被实例化一次然后在其他任何地方使用,我最初的想法是建议将其作为构造函数参数(依赖注入)传递,但由于您不喜欢这种方法,我建议您将数据库客户端设为 singleton class ,这意味着它只能被实例化一次,并且任何后续尝试都会在任何地方返回相同的实例。

You can see a detailed response about singleton classes in PHP at Creating the Singleton design pattern in PHP5 .您可以在 PHP5 中创建 Singleton 设计模式的 PHP中查看有关 singleton 类的详细响应。

As a quick example, your DB would look like similar to this:举个简单的例子,您的数据库看起来与此类似:

final class DB
{
    public static function getInstance()
    {
        static $inst = null;

        if ($inst === null) {
            $inst = new self();
        }

        return $inst;
    }

    private function __construct()
    {
        // your code here ...
    }

    // your code here ...
}

And then, on your User class you would just get the DB class instance:然后,在您的用户 class 上,您将获得 DB class 实例:

class User {
    // your code here ...

    public function doSomething() {
        $db = DB::getInstance();

        // your code here ...
    }
}

PHP does not handle scopes like Javascript does, your $db is undefined. PHP 不像 Javascript 那样处理范围,你的 $db 是未定义的。

The scope of a variable is the context within which it is defined.变量的 scope 是定义它的上下文。 For the most part all PHP variables only have a single scope.在大多数情况下,所有 PHP 变量只有一个 scope。 This single scope spans included and required files as well […] Within user-defined functions a local function scope is introduced.这个单一的 scope 也涵盖了包含的文件和所需的文件 […] 在用户定义的函数中,引入了本地 function scope。 Any variable used inside a function is by default limited to the local function scope. function 中使用的任何变量默认限制为本地 function scope。

Source : http://php.net/manual/en/language.variables.scope.php来源http://php.net/manual/en/language.variables.scope.php

This means that there is only a global scope and a function/method scope in PHP.这意味着在 PHP 中只有一个全局 scope 和一个函数/方法 scope。 So, either pass the $db instance into the method as a collaborator因此,要么将 $db 实例作为协作者传递给方法

class User{

    public function __construct() {}

    public function getInfo(Database $db) {
        $db->query( /* ... */ );
    }
}

$user = new User();
$db = new Database();
$user->getInfo($db);

or pass it in the constructor (dependency injection)或者在构造函数中传递它(依赖注入)

class User{
    private $db;

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

    public function getInfo() {
        $this->db->query( /* ... */);
    }
}

$db = new Database();
$user = new User($db);
$user->getInfo();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM