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.
精彩评论