【发布时间】:2014-09-25 13:04:50
【问题描述】:
我最近一直在玩弄动态 PDO 连接方法。但是当我开始使用其他类时遇到了一些问题。
为什么我不能使用Server类中构造的方法连接到Admin类中的数据库?
我尝试了很多解决方案。这对我来说似乎最合乎逻辑......
如何让它工作,这样我就不必在每个类中都构建连接?
class Server
{
private $hostdb = 'blah';
private $namedb = 'blah';
private $userdb = 'blah';
private $passdb = 'blah';
public static $conn;
public $errorMessage = 'If you read this text, contact web administrator and tell him about your problem.';
public function __construct()
{
$this->connect();
}
public function connect()
{
try {
$this->conn = new PDO("mysql:host=$this->hostdb; dbname=$this->namedb", $this->userdb, $this->passdb, array(PDO::ATTR_PERSISTENT => true));
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
还有 Admin 类:
class Admin extends User
{
function someFunction($table)
{
try {
$sql = "SELECT * FROM $table";
//I want to change this line so that my connection would work
$result = Server::$conn->query($sql);
while ($row = $result->fetch(PDO::FETCH_NUM)) {
//Do something
}
} catch (PDOException $e) {
//Show when debugging
//echo $e->getMessage();
echo Server::errorMessage;
}
}
}
我已经在 config.req.php 文件中实例化了 Server、User 和 Admin 类。
当我将“Server::$conn->”更改为“static::$conn->”时,它仍然给了我一个错误。
【问题讨论】:
标签: php class methods pdo connection