直到現在,我通過$database
- 對象通過在__constructor
的論點,但我想擺脫通過它在每個班。但怎麼做呢?我不是一個很聰明的OOP兒,我雖然瞭解一些基礎知識... 這裏是我的代碼,我現在用的:修訂在類中使用MySQLi,如何實現?
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()
那麼,你需要以某種方式獲取數據庫。要麼你通過它,要麼你的班級需要獲得連接本身。如果你想讓類自己獲取連接,可以將它封裝在一個單例中,這樣你就可以做類似'DBManager :: getConnection()'的事情了。 – 2011-02-24 18:37:00