db_class.php
<?php
class db_mysql
{
private $dbhost;
private $dbusername;
private $dbpassword;
private $db;
//Class is called with all parameters to make a successful connection.
//
function __construct($dbhost,$dbusername,$dbpassword,$db)
{
global $dbh;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$db", $dbusername, $dbpassword);
foreach($dbh->query('show tables;') as $row) {
print_r($row);
}
//$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
//Function to execute a query in the database and return result in a array
//
function db_mysql_query($queryst)
{
foreach($dbh->query($queryst) as $row) {
print_r($row);
}
}
}
index.php:
<?php
include 'db_class.php';
$db_m = new db_mysql('localhost','root','','arsaas');
$db_m->db_mysql_query('show tables;');
?>
执行index.php会出现以下错误:注意:未定义的变量:第32行C:''examplep''htdocs''srry''db_class.php中的dbh
致命错误:在的第32行对C:''examplep''htdocs''srry''db_class.php中的非对象调用成员函数query()
当dbh在类构造函数中被实例化并声明为全局变量时,为什么它说它是未定义的变量?
感谢您的帮助。提前谢谢。
AR
db_mysql_query方法没有定义变量$dbh,因此尝试在非对象上调用方法query是不起作用的。您可以将PDO对象($dbh)存储到构造函数中的db_mysql对象中,并在调用db_mysql_query时使用它。如果您试图只使用一个数据库连接,那么我建议您考虑在db_mysql类中使用singleton模式。http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html