我正在尝试创建一个简单易用的单例类来连接到mysql数据库并执行查询,代码可以正常工作,并且我没有任何问题,但是由于我是OOP的新手,所以我想知道这是否是不是坏习惯。
这是课程
class Database { private $databaseName = 'dbname'; private $host = 'localhost'; private $user = 'user'; private $password = 'pass'; private static $instance; //store the single instance of the database private function __construct(){ //This will load only once regardless of how many times the class is called $connection = mysql_connect($this->host, $this->user, $this->password) or die (mysql_error()); $db = mysql_select_db($this->databaseName, $connection) or die(mysql_error()); echo 'DB initiated<br>'; } //this function makes sure there's only 1 instance of the Database class public static function getInstance(){ if(!self::$instance){ self::$instance = new Database(); } return self::$instance; } public function connect() { //db connection } public function query($query) { //queries $sql = mysql_query($query) or die(mysql_error()); return $sql; } public function numrows($query) { //count number of rows $sql = $this->query($query); return mysql_num_rows($sql); } } //Intantiate the class $database = Database::getInstance();
当我想使用该类时,我会做:
$query = "SELECT * FROM registrations"; echo $database->numrows($query); $sql = $database->query($query);
单身人士是个坏消息。
您最好改用依赖项注入,因为它可以解决上述问题。