例如,您可以使用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;
}
}