dtv55860 2013-05-11 13:24
浏览 59
已采纳

如何在PHP中设置变量类型

I created a class MySQLConnector with the field connection. I have a connect function that can set the $this->connection variable:

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

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

The problem is: $this->connection isn't a mysqli type. It doesn't have a type. How can I cast or set the type correctly? I want to use $this->connection->query(). In other places of this class and from outside of this class.

  • 写回答

1条回答 默认 最新

  • drfcaw7460 2013-05-11 13:29
    关注

    You could, for example user PDO instead of mysqli for its benefits. Or, you could simiply typecast like

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

    A better way around would be to have those kind of stuff in the constructor as it is initialization:

    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;
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序