开发者

Use MySQLi in classes, how to implement?

开发者 https://www.devze.com 2023-02-13 01:19 出处:网络
Till now I passed the $database-object through an argument in the __constructor But I want to get rid of passing it through in every class. But how to do it? I\'m not a very smart OOP-er, I know some

Till now I passed the $database-object through an argument in the __constructor But I want to get rid of passing it through in every class. But how to do it? I'm not a very smart OOP-er, I know some basics though... Here's my code I use now: UPDATED

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 = ne开发者_运维知识库w 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;
        }
    }
}

It doesn't work: Call to undefined method connection::prepare()


MySQLi::getInstance($optional_instance_name) as a static method that retrieves whatever database connection you ask for.

0

精彩评论

暂无评论...
验证码 换一张
取 消