我试图找出最好的办法是让程序中的多个对象连接到数据库。
我创建了一个带有静态连接变量的类。这似乎意味着只打开一个连接并且所有对象共享它。
class Database {
public static $mysql;
function __construct() {
if (!isset(self::$mysql)) {
echo "Make static connection\n";
self::$mysql = new mysqli("localhost", "gamalert", "c45ualty", "events");
if (self::$mysql->connect_errno) {
echo "Failed to connect to MySQL: (" . $this->mysql->connect_errno . ") " . self::$mysql->connect_error;
}
echo self::$mysql->host_info . "\n";
}
}
}
一个普通的对象版本。这将为每个使用它的对象创建一个新连接。
class Database {
public $mysql;
function __construct() {
if (!isset($this->mysql)) {
echo "Make connection\n";
$this->mysql = new mysqli("localhost", "gamalert", "c45ualty", "events");
if ($this->mysql->connect_errno) {
echo "Failed to connect to MySQL: (" . $this->mysql->connect_errno . ") " . $this->mysql->connect_error;
}
echo $this->mysql->host_info . "\n";
}
}
我想知道首选的选项是什么?我计划稍后测试性能差异。