[英]How can I use a different object inside of a class?
If I create an object inside of the main scope: 如果我在主作用域内创建一个对象:
INDEX.PHP: index.php文件:
$db = new database();
Then how can I use this same object inside of a completely different class? 那么,如何在完全不同的类中使用同一对象呢?
ANYTHING.PHP: ANYTHING.PHP:
class anything {
function __construct(){
$db->execute($something); # I want to use the same object from INDEX.PHP
}
}
Would I need to make $db a global or is there a 'better' more obvious way? 我是否需要使$ db成为全局变量,还是有一种“更好的”更明显的方式?
You could just use global
to find it: 您可以使用
global
来找到它:
class anything {
function __construct(){
global $db;
$db->execute($something);
}
}
Or, you could pass it in when creating a new anything: 或者,您可以在创建新内容时将其传递给:
class anything {
function __construct($db) {
$db->execute($something);
}
}
It really depends on what makes the most sense for you. 这实际上取决于什么对您最有意义。
For the DB you may want to use Singleton pattern 对于数据库,您可能需要使用Singleton模式
class anything
{
public function load($id)
{
$db = DB::getInstance();
$res = $db->query('SELECT ... FROM tablename WHERE id = '.(int)$id);
// etc...
}
}
You may want to extend it if you need different DB connections at the same time (ie main db and forum's db). 如果您同时需要不同的数据库连接(例如,主数据库和论坛的数据库),则可能需要扩展它。 Then you'll use it like
DB::getInstance('forum');
然后,您将像
DB::getInstance('forum');
一样使用它DB::getInstance('forum');
and store instances in associative array. 并将实例存储在关联数组中。
You could pass it as an argument, like this 您可以像这样传递它作为参数
function __construct($db){
$db->execute($something);
}
then when you instance anything, do it as anything($db)
然后当您实例化任何内容时,将其作为
anything($db)
As Paolo and ONi suggested you can define $db as global inside the method or pass it into the constructor of the class. 正如Paolo和ONi所建议的那样,您可以在方法内部将$ db定义为global,或者将其传递到类的构造函数中。 Passing it in will create a reference to that object so it will in fact be the same $db object.
传递它将创建对该对象的引用,因此实际上它将是相同的$ db对象。 You could also use the $GLOBALS array and reference $db that way.
您也可以使用$ GLOBALS数组并以这种方式引用$ db。
$GLOBALS["db"];
I'm assuming that index.php and anything.php are linked together somehow by include() or require() or some similar method? 我假设通过include()或require()或某些类似方法以某种方式将index.php和everything.php链接在一起?
In Paolo's post: 在Paolo的帖子中:
After you pass it, you can then assign it to a class variable like this: 传递完之后,可以将其分配给这样的类变量:
class anything {
var $db_obj;
function __construct($db) {
$this->db_obj = $db;
}
function getUsers() {
return $this->db_obj->execute($something);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.