【发布时间】:2013-07-26 19:37:03
【问题描述】:
我有以下数据库查询,它工作正常,但在前面的另一个问题中,我注意到我正在使用全局,但它不是必需的。原因是我试图使用受保护的变量,但作为 OOP 的新手,无法使其工作。
也许有人可以告诉我应该怎么做?
<?
class DB {
public function __construct() {
global $dbh;
try {
$dbh = new PDO('mysql:host=localhost;dbname=main_db', 'my_user', 'my_pass');
$dbh ->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
public function getFAQCats2Array() {
global $dbh;
try {
$q = '
SELECT
`id` AS ci,
`name` AS n
FROM
`faqcat`;
';
$s = $dbh->query($q);
// initialise an array for the results
$A = array();
while ($r = $s->fetch(PDO::FETCH_ASSOC)) {
$A[] = $r;
}
$s = null;
return $A;
}
catch(PDOException $e) {
echo "Something went wrong fetching the list of FAQ categories from the database.\n";
file_put_contents(
$_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
"\n\n\n\n".$e->__toString(), FILE_APPEND);
}
}
public function getFAQ($i, $f) {
global $dbh;
try {
$q = '
SELECT
'.$f.'
FROM
faq
WHERE
id = ?
';
$s = $dbh->prepare($q);
$s->execute(array($i));
//$s->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$r = $s->fetch();
return $r[$f];
}
catch(PDOException $e) {
echo "Something went wrong fetching the FAQ answer from the database.\n";
file_put_contents(
$_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
"\n\n\n\n".$e->__toString(), FILE_APPEND);
}
}
}
(类中还有其他函数在$dbh 中使用相同的连接字符串,但为了简单起见,我已将其删除)
【问题讨论】:
标签: php oop global-variables