PHP和PDO类问题 [英] PHP and PDO class question
问题描述
我是一个非常新的OOP风格的PHP,我也试图实现PDO以及。我发现这个好的小类在线处理数据库连接,但我不知道如何从另一个类访问它。这里是代码:
I am very new to OOP styled PHP, and I am trying to implement PDO as well. I found this nice little class online which handles the database connection, however I have no idea how to access it from another class. Here is the code:
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
?我希望避免。 (我仍然只有对类的变量范围的一个非常基本的了解)
How can I gain access to the $db_handle
variable inside of my Person class? Do i have to instantiate the variable inside of the Person class? If so, does that mean I will always have to call it as $this->db_handle
? I was hoping to avoid that. (I still only have a very basic understanding of variable scope with classes)
推荐答案
这个。最便携,最推荐的是称为依赖注入,通过它的 __ construct()
将数据库句柄传递到类中,并将其存储在类变量中。需要使用 $ this-> db
访问它,就像你不想做的那样。
There are (at least) three ways to handle this. The most portable, and oft recommended is called "dependency injection", whereby you pass the database handle into your class via its __construct()
and store it in a class variable. Requires accessing it with $this->db
like you didn't want to have to do.
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
作为全局
,无论何时在类中使用它。这可能是最难读取和调试的。
Finally, you can call $db_handle
as a global
whenever you use it in your class. This is perhaps the hardest to read and debug.
class Person {
public function __construct() {
global $db_handle;
}
public function otherFunc() {
global $db_handle;
$db_handle; // do something
}
}
这篇关于PHP和PDO类问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!