我不建议以这种方式创建数据库连接。创建一个连接,并使用该连接将其注入到对象中。您不需要为每个对象创建一个新的连接。
代码示例:
$connection = new MysqLi('localhost', 'user', 'password');
$Account = new Account($connection);
将需要更改Account
为如下所示:
class Account {
protected $connection;
public function __construct(MysqLi $connection) {
$this->connection = $connection;
}
public function register() {
// use $this->connection for db
}
public function login() {
// use $this->connection for db
}
}
我还建议您看看有关选择MySQL API的php.net文档。如果您真的想将OOP与PHP和MysqL一起使用,则需要交换MysqLi
或PDO
使用的API并不真正支持OOP接口。