【发布时间】:2011-02-24 18:31:56
【问题描述】:
到目前为止,我通过 __constructor 中的参数传递了 $database-object
但我想摆脱它在每节课上都通过。但是怎么做呢?我不是一个非常聪明的 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()
【问题讨论】:
-
嗯,您需要以某种方式获取数据库。要么你把它传入,要么你的类需要自己获取连接。如果您要让类自己获取连接,请将其包装在一个单例中,以便您可以执行类似
DBManager::getConnection()之类的操作。