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 を実行すると、次のエラーが発生します: Notice: Undefined variable: dbh in C:\xampp\htdocs\srry\db_class.php on line 32
致命的なエラー: 32 行目の C:\xampp\htdocs\srry\db_class.php の非オブジェクトに対するメンバー関数 query() の呼び出し
dbh がインスタンス化され、クラス コンストラクターでグローバル変数として宣言されたときに、dbh が未定義変数であると表示されるのはなぜですか?
どんな助けでも大歓迎です。前もって感謝します。
AR