如何从另一个类访问对象? [英] How to access an object from another class?

查看:86
本文介绍了如何从另一个类访问对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库类,用于选择,更新,删除 MySQL 查询。

I have a database class, which is used to make select, update, delete MySQL queries.

现在,我想在另一个类中创建一个MySQL查询,但是如果我定义 $ db = new DB(); index.php ,我不能在另一个类中使用 $ db var。如果我想进行查询,我必须一遍又一遍地定义变量 $ db 或者是否有一种方法使 $ db var与对象全局var?

Now, I want to create a MySQL query inside another class, but if I define $db = new DB(); in index.php, I can't use the $db var in another class. Do I have to define the variable $db over and over again, if I want to make a query? Or is there a way to make the $db var with an object global var?

推荐答案

最简单的方法是通过聚合数据库类所需的注入。所有其他方法,例如使用 全局 关键字或使用 static 方法,更不用说Singleton,引入了类和全局范围之间的紧耦合,使得应用程序更难测试和维护。只要做

The cleanest approach would be to aggregate the database class where needed by injecting it. All other approaches, like using the global keyword or using static methods, let alone a Singleton, is introducing tight coupling between your classes and the global scope which makes the application harder to test and maintain. Just do

// index.php
$db  = new DBClass;               // create your DB instance
$foo = new SomeClassUsingDb($db); // inject to using class

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

使用如果依赖是可选的或需要在运行时可互换,请使用Setter注入,例如

Use Constructor Injection if the dependency is required to create a valid state for the instance. If the dependency is optional or needs to be interchangeable at runtime, use Setter Injection, e.g.

class SomeClassUsingDb
{
    protected $db;
    public function setDb($db)
    {
        $this->db = $db;
    }
}

这篇关于如何从另一个类访问对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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