我对 OOP 风格的 PHP 很陌生,我也在尝试实现 PDO。我在网上找到了这个处理数据库连接的不错的小类,但是我不知道如何从另一个类访问它。这是代码:
class PDO_DBConnect {
static $db ;
private $dbh ;
private function PDO_DBConnect () {
$db_type = 'mysql'; //ex) mysql, postgresql, oracle
$db_name = 'postGal';
$user = 'user' ;
$password = 'pass' ;
$host = 'localhost' ;
try {
$dsn = "$db_type:host=$host;dbname=$db_name";
$this->dbh = new PDO ( $dsn, $user, $password);
$this->dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $e ) {
print "Error!: " . $e->getMessage () . "\n" ;
die () ;
}
}
public static function getInstance ( ) {
if (! isset ( PDO_DBConnect::$db )) {
PDO_DBConnect::$db = new PDO_DBConnect ( ) ;
}
return PDO_DBConnect::$db->dbh;
}
}
$db_handle = PDO_DBConnect::getInstance();
class Person
{
function __construct()
{
$STMT = $db_handle->prepare("SELECT title FROM posts WHERE id = ? AND author = ? LIMIT 20");
$STMT->execute(array('24', 'Michael'));
while ($result = $STMT->fetchObject())
{
echo $result->title;
echo "<br />";
}
}
}
我怎样才能访问我的 Person 类中的 $db_handle
变量?我必须在 Person 类中实例化变量吗?如果是这样,是否意味着我必须始终将其称为 $this->db_handle
?我希望避免这种情况。 (我对类的变量作用域仍然只有非常基本的了解)
最佳答案
有(至少)三种方法来处理这个问题。最可移植且经常被推荐的称为“依赖注入(inject)”,您可以通过 __construct()
将数据库句柄传递到您的类中,并将其存储在类变量中。需要使用 $this->db
访问它,就像您不想做的那样。
class Person {
// Member to hold the db handle
public $db;
public function __construct($db_handle) {
// Assign the handle to a class member variable in the constructor
$this->db = $db_handle;
}
public function otherFunc() {
$this->db; // do something
}
}
$person = new Person($db_handle);
下一个方法是在构造函数中实例化 $db_handle
而不是将其传入。这有点难以测试和调试。
class Person {
public $db;
public function __construct() {
$this->db = PDO_DBConnect::getInstance();
}
}
最后,无论何时在类里面使用它,都可以将 $db_handle
作为 global
调用。这可能是最难阅读和调试的。
class Person {
public function __construct() {
global $db_handle;
}
public function otherFunc() {
global $db_handle;
$db_handle; // do something
}
}
关于PHP和PDO类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6297835/