如何在PHP中设置变量类型

时间:2013-05-11 13:24:35

标签: php types casting mysqli

我使用字段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()。在本课程的其他地方和本课程以外的地方。

1 个答案:

答案 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;
    }

}