如何使用新方法扩展PDO类并在另一个类中使用该方法?

时间:2019-02-06 00:40:16

标签: php class

我曾经将数据库连接存储在一个文件中,并将其包含在需要的页面中。在此文件中,我还使用新方法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']);
            [...]
        }
    }

    [...]
}

目前,我没有使用自动加载功能来加载类。该特定文件仅需要两个类,因此我需要手动进行操作。我还被认为可以手动添加连接类,从而可以使用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);
    }

}

但是运行此命令时会收到以下错误:

  

未捕获的错误:调用未定义的方法Connection :: run()

我了解错误的含义,即连接类内部没有名为run()的方法,但是为什么认为该方法在其中呢?我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

@ Quasimodo'sclone是正确的,您需要从conn变量中获取它们,如它们所演示的那样。如果不起作用,则您在其他地方的实现上做错了,因为run()conn的方法,因为conn是定义{{1}的类MyPDO }方法:

run()等于类$this->db,它在Connection中创建MyPDO的实例,并在__construct()方法中将其分配给$this->conngetPDOConnection()是您要寻找的。

您的$this->db->conn->run()应该重命名为getPDOConnection(),然后让setPDOConnection()检索getPDOConnection()

$this->conn

然后您的User类将实际使用:

public function getPDOConnection()
{
    return $this->conn;
}

这将使其更加清晰

相关问题