簡體   English   中英

在類中使用MySQLi,如何實現?

[英]Use MySQLi in classes, how to implement?

到目前為止,我已經通過__constructor的參數傳遞了$database -object,但是我想擺脫在每個類中傳遞它的__constructor 但是怎么做呢? 我不是一個非常聰明的OOP-er,盡管我知道一些基本知識...這是我現在使用的代碼: 更新

class connection {
    public static $connection;

    public function __construct() {
        $this->connection = new MySQLi('localhost', 'user', 'pass');
        $this->connection->select_db('database');
    }

    public function getInstance() {
        if(!isset(self::$connection)) {
            self::$connection = new connection;
        }
        return self::$connection;
    }
}

class something {
    private $connection;

    public $id;

    function __construct($id) {
        $this->connection = connection::getInstance();
        $this->id = $id;
    }

    function verify() {
        $statement = $this->connection->prepare('SELECT * FROM `tabel` WHERE `id` = ?');
        $statement->bind_param('s', $this->id);
        $statement->execute();

        $statement->store_result();
        if($statement->num_rows != 1) {
            return false;
        }
    }
}

它不起作用: Call to undefined method connection::prepare()

MySQLi::getInstance($optional_instance_name)作為靜態方法,可檢索您要求的任何數據庫連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM