我曾经将我的数据库连接放在一个文件中,并将它包含在我需要的页面中。在这个文件中,我还用一个新方法run()扩展了PDO类,它允许我编写简写的PDO查询,并且工作得很好:
class MyPDO extends PDO {
public function run($sql, $bind = NULL) {
$stmt = $this->prepare($sql);
$stmt->execute($bind);
return $stmt;
}
}
$conn = new MyPDO("mysql:charset=utf8;host=$host;dbname=$name", $user, $pass);我现在正试图通过使用类来整理我的文件和它们中的代码。因此,这个数据库连接文件变成了两个类:
class MyPDO extends PDO {
public function run($sql, $bind = NULL) {
$stmt = $this->prepare($sql);
$stmt->execute($bind);
return $stmt;
}
}
class Connection {
private $_config = NULL;
public $conn = NULL;
public $error = NULL;
public function __construct(array $config) {
$this->_config = $config;
$this->getPDOConnection();
}
private function getPDOConnection() {
if ($this->conn == NULL) {
$this->conn = new MyPDO("mysql:charset=utf8; host=".$this->_config['host']."; dbname=".$this->_config['name']."", $this->_config['user'], $this->_config['pass']);
[...]
}
}
[...]
}此时,我没有使用autoload函数来加载类。这个特定的文件只需要两个类,所以我需要手动处理它们。我还认为手动包含连接类允许用MyPDO扩展PDO类。
require API_ROOT . 'core/database/connection.class.php';
require API_ROOT . 'core/users/user.class.php';我已经测试过这个连接,它确实已经连接到了。
我遇到的问题是,在另一个类中使用名为MyPDO的新run()方法,在本例中是user.class。
在user.class内部,我只是试图对用户进行身份验证,因此需要使用run()方法。
我像这样调用用户类:
$db = new Connection($config['database']);
$user = new User($db, $config);在user.class内部,我希望使用run(),并通过调用$this->db->run来实现
class User {
private $db = NULL;
private $config = NULL;
public function __construct($db = NULL, $config = NULL) {
$this->db = $db;
$this->config = $config;
}
public function login($email = '', $password = '', $remember_me = '') {
$user_profile = $this->db->run(" <--------------
[...]
", [$email])->fetch(PDO::FETCH_ASSOC);
}
}但是,当我运行以下命令时,会收到以下错误:
未定义的错误:调用未定义的方法连接::run()
我理解这个错误的含义,在我的连接类中没有一个叫做run()的方法,但是为什么它认为这个方法在那里呢?我在这里做错什么了?
发布于 2019-02-06 06:07:07
@Quasimodo的克隆是正确的,您需要从conn变量中获取它,就像他们演示的那样。如果它不起作用,您在其他地方的实现上做错了什么,因为run()是conn的一种方法,因为conn是定义run()方法的类MyPDO:
$this->db等于类Connection,它在__construct()中创建MyPDO实例,并在getPDOConnection()方法中将其分配给$this->conn -因此,$this->db->conn->run()是您要寻找的对象。
您的getPDOConnection()可能应该重命名为setPDOConnection(),然后让getPDOConnection()检索$this->conn
public function getPDOConnection()
{
return $this->conn;
}然后,您的用户类将实际使用:
$this->db->getPDOConnection()->run(...etc);这样会让事情变得更清楚一些。
https://stackoverflow.com/questions/54545162
复制相似问题