0

MySQLConnector用字段创建了一个类connection$this->connection我有一个可以设置变量的连接函数:

public function connect($host, $user, $password, $database)
{
    $mysqli = new mysqli($host, $user, $password, $database);

    if(!$mysqli->connect_errno)
        $this->connection = $mysqli;
}

问题是:$this->connection不是mysqli类型。它没有类型。如何正确转换或设置类型?我想用$this->connection->query(). 在这个班级的其他地方和来自这个班级的外面。

4

1 回答 1

1

例如,您可以使用PDO而不是 mysqli 来获得它的好处。或者,您可以简单地进行类型转换,例如

public function setMysqli(mysqli $mysqli) {
    $this->mysqli = $mysqli;
}

更好的解决方法是在构造函数中包含这些东西,因为它是初始化:

class MySQLConnector implements DatabaseConnector {

    private $connection;

    /**
     * Initialize connector instance.
     * Not using OO API of mysqli here because it's junk anyways - you should use PDO.
     * @param $host The host of the SQL server.
     * @param $username The user for the database.
     * @param $password The password of the user.
     * @param $database The database to be used.
     * @throws RuntimeException if connection fails.
     */
    public function MySQLConnector($host, $username, $password, $database) {
        if (!$this->connection = mysqli_connect($host, $username, $password, $database)) {
            throw new RuntimeException(mysqli_connect_error());
        }
    }

    /**
     * Retrieve the connection reference for use.
     * The field $connection will always be a valid mysqli instance since
     * it is already initialized by the constructor.
     * @return A connection handle to the database for use with persistence operations.
     */
    public function getConnection() {
        return $this->connection;
    }

}
于 2013-05-11T13:29:06.717 回答