基本上,我有一个"user"类,其中一部分如下:
class user{
private $username;
public function get_last_visit(){
return $GLOBALS['db']->get(
'users',
'last_visit',
'username' => $this->username
);
}
}
我需要从"user"类内部调用对象"db"的方法。使用上面的方法是最好的方法吗?我听人说,使用$GLOBALS变量是一种糟糕的做法。
您想了解的是依赖注入,它使您能够将所需的对象注入到用户对象的构造中。
# Your updated User class
class User {
private $username;
private $db
public function __construct($db){
$this->db = $db
}
public function get_last_visit(){
return $this->db->get(
'users',
'last_visit',
'username' => $this->username
);
}
}
# Instantiate your Database Wrapper
$db = new DatabaseWrapper();
# Instantiate your User object with the DatabaseWrapper injected
$john_doe = new User($db);
$john_doe->get_last_visit();
由于作用域的问题,它不受欢迎。毫无疑问,正如您所经历的,函数和类中的变量不会与它们各自区域之外的任何东西直接交互。否则,变量会到处碰撞。这就是为什么对象和方法通常会取代去年的过程代码。当您必须显式传递数据时,跟踪程序中发生的事情要容易得多,而不是依赖于各种$GLOBALS
。
我强烈建议您依赖注入数据库指针。这样你就不会不断地重新创建你的连接,你的类和方法就变得不可知连接是如何形成的
class user{
private $username;
/** @var stdClass */
protected $db;
public function __construct($db) {
$this->db = $db;
}
public function get_last_visit(){
return $this->db->get(
'users',
'last_visit',
'username' => $this->username
);
}
}
$user = new user($db);