【发布时间】:2017-04-26 21:09:30
【问题描述】:
这是指运行 PHP 5.4 和 MariaDB 5.5 的 CentOS 7 服务器。
我对 PHP 中的 OOP 有点陌生。在将一堆脚本从 MySQL 转换为 MySQLi 并将过程数据库函数转换为 OOP 时,我设置了这个基本的 Database 类:
class Database
{
private $host = "localhost";
private $username;
private $password;
private $database;
private $dbconnect;
function __construct()
{
// Load config file for database connection info
$ini = parse_ini_file("config.ini");
$this->username = $ini['db.user'];
$this->password = $ini['db.pword'];
$this->database = $ini['db'];
}
public function connect()
{
// Only make a new connection if one not already established.
if (empty($this->dbconnect)) {
$mysql = new mysqli($this->host, $this->username, $this->password, $this->database);
if ($mysql->connect_errno) {
throw new appError($mysql->connect_error);
}
$this->dbconnect = $mysql;
}
return $this->dbconnect;
}
public function query($query)
{
$db = $this->connect();
$result = $db->query($query);
if ($db->errno) return false;
return $result;
}
public function select($query)
{
$rows = array();
$result = $this->query($query);
if ($result === false) return false;
// Create array with results
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
}
使用以前使用 mysql_* 的过程数据库函数,在脚本开始附近建立持久数据库连接,并将资源 ID 存储在全局变量中,然后所有查询都通过该数据库连接运行,方法是访问全局资源变量。重要的是,这在其他函数和对象中运行良好。该函数的工作原理如下:
function db_connect() {
if (!empty($GLOBALS['DBCONNECT']) && is_resource($GLOBALS['DBCONNECT'])) {
return $GLOBALS['DBCONNECT'];
} else {
$result = mysql_connect("localhost", DB_USER, DB_PASSWORD);
$GLOBALS['DBCONNECT'] = $result;
return $result;
}
}
所以在每个脚本的开头我都会这样做......
db_connect();
然后像这样运行我的查询...
$result = mysql_query($query, db_connect());
这确保建立了一个数据库连接,并且所有查询都通过该连接运行。
使用上面的新数据库类,我在脚本开始时实例化它...
$db = new Database;
$db->connect();
但我不明白如何使需要执行数据库查询的其他对象可以访问该数据库对象,以便整个脚本使用相同的数据库连接。我现在做的基本上就是这个……
class MyClass
{
public function myFunction()
{
$db = new Database;
$data = $db->select("SELECT * FROM mydata WHERE id = 888");
...
}
}
这会在上述类中实例化一个新的 Database 对象,该对象正在创建与数据库的新的附加连接,因为它无法访问在父调用脚本中创建的 Database $db 对象(据我所知) .
有没有办法使用对象打开持久的 MySLQi 数据库连接,该脚本加载的所有函数和对象都可以使用该连接?或者这只是用过程函数而不是类和对象更好地完成的事情?解决方案是否在于使数据库属性及其方法静态?如果我这样做,我不确定如何从 connect() 函数需要的 config.ini 文件加载数据库用户名和密码,并且仅在数据库对象实例化时完成。
我想这里的基本问题是如何从另一个对象访问实例化对象中的属性或方法?或者也许这不是问题,我完全错过了其他东西。谢谢!
【问题讨论】: