我使用字段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()
。在本课程的其他地方和本课程以外的地方。
答案 0 :(得分: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;
}
}