我用字段connection
创建了一个类MySQLConnector
。我有一个连接函数,可以设置$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()
。在这门课的其他地方以及在这门课之外
您可以,例如,使用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;
}
}