我有这样的课程:
类页面.php
class pages {
private $dbh;
function __construct($dbh) {
$this->dbh = $dbh;
}
//...
}
类新闻.php
class news {
private $dbh;
function __construct($dbh) {
$this->dbh = $dbh;
}
//...
}
类Mod.php
class mod {
private $dbh;
function __construct($dbh) {
$this->dbh = $dbh;
}
//...
}
在索引页面中:
try
{
$dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
require 'classPages.php';
require 'classNews.php';
require 'classMod.php';
$pages = new pages($dbh);
$news = new news($dbh);
$mod = new mod($dbh);
//use above objects where needed
所以我创建了单个 PDO 对象。然后将其传递给每个类的构造函数。然后我使用这些对象并调用它的成员函数,这些函数使用传递给构造函数的这个 pdo 对象来获取和插入数据。
是正确的方式吗?还是直接/间接发生任何冲突?