[英]How to access an object from another class?
I have a database class, which is used to make select, update, delete MySQL queries.我有一个数据库类,用于进行选择、更新、删除MySQL查询。
Now, I want to create a MySQL query inside another class, but if I define $db = new DB();
现在,我想在另一个类中创建一个 MySQL 查询,但是如果我定义$db = new DB();
in index.php
, I can't use the $db
var in another class.在index.php
,我不能在另一个类中使用$db
var。 Do I have to define the variable $db
over and over again, if I want to make a query?如果我想进行查询,是否必须一遍又一遍地定义变量$db
? Or is there a way to make the $db
var with an object global var?或者有没有办法用一个对象全局$db
来制作$db
var?
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.所有其他方法,例如使用global
关键字或使用static
方法,更不用说单例了,都在您的类和全局范围之间引入了紧密耦合,这使得应用程序更难测试和维护。 Just do做就是了
// index.php
$db = new DBClass; // create your DB instance
$foo = new SomeClassUsingDb($db); // inject to using class
and和
class SomeClassUsingDb
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
}
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, eg如果依赖项是可选的或需要在运行时互换,请使用 Setter 注入,例如
class SomeClassUsingDb
{
protected $db;
public function setDb($db)
{
$this->db = $db;
}
}
You probably want a singleton .你可能想要一个单身人士。 This gives you a way to get an instance of DB anywhere in the code.这为您提供了一种在代码中的任何位置获取 DB 实例的方法。 Then anywhere you want to do a query, first do $db = DB::getInstance();
然后在任何你想做查询的地方,首先做$db = DB::getInstance();
. .
An alternative is dependency injection , which passes a DB instance to all classes which need one.另一种方法是依赖注入,它将一个数据库实例传递给所有需要一个的类。
In your index.php
file use在您的index.php
文件中使用
require_once('path_to_file_with_class.php');
You may also use include_once
, which will give you a warning instead of an error if the 'path_to_file_with_class.php' file is not available.您也可以使用include_once
,如果 'path_to_file_with_class.php' 文件不可用,它会给您一个警告而不是一个错误。
使用魔术函数__autoload()
。
您可以在 index.php 文件中将其定义为 global,并且在类构造函数中还放置$this->db &= $GLOBALS['db'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.