我对使用 MYSQL 的 PDO 有点陌生,这是我的两个文件:
我有一个用于连接数据库的连接类:
class connection{
private $host = 'localhost';
private $dbname = 'devac';
private $username = 'root';
private $password ='';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We\'re sorry but there was an error while trying to connect to the database';
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
}
}
我有一个用于查询数据库数据的 account_info 类:
class account_info{
function getAccountInfo(){
$acc_info = $this->con->prepare("SELECT * FROM account_info");
$acc_info->execute();
$results = $acc_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key) {
$results->owner_firstname;
}
}
}
我将这两个文件都包含在我的 index.php 页面中:
include_once 'classes/connection.class.php';
include_once 'classes/accountinfo.class.php';
$con = new connection();
$info = new account_info();
$info->getAccountInfo();
我只是无法让它工作 我没有得到任何输出,我认为它与范围有关,但我不知道修复它的正确原因,因为我是这个 PDO 的新手并且面向对象的东西。 提前致谢。
最佳答案
解决方案一
将 class account_info {
替换为 class account_info extends connection {
替换
$con = new connection();
$info = new account_info();
与
$info = new account_info();
它应该可以工作。
方案二(推荐)
在这种情况下,我强烈建议您使用依赖注入(inject)来解决您的问题。 只需将您的帐户类替换为:
class account_info {
private $con;
public function __construct(connection $con) {
$this->con = $con->con;
}
public function getAccountInfo(){
$acc_info = $this->con->prepare("SELECT * FROM account_info");
$acc_info->execute();
$results = $acc_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key) {
$results->owner_firstname;
}
}
}
并像这样在 index.php 中使用它:
include_once 'classes/connection.class.php';
include_once 'classes/accountinfo.class.php';
$con = new connection();
$info = new account_info($con);
$info->getAccountInfo();
解释
作为一般的好规则:始终为函数(公共(public)、 protected 或私有(private))指定范围关键字。
第一个解决方案称为继承,我们基本上做的是使用连接类扩展帐户类,以便从连接类继承所有方法和属性并轻松使用它们。在这种情况下,您必须注意命名冲突。我建议你看看PHP手册中的类继承。
第二种解决方案称为依赖注入(inject),它是一种广受鼓励的设计模式,它使您的类在其构造函数中接受其他类,以便显式定义类依赖树(在这种情况下,帐户依赖于连接,而没有连接我们无法使帐户工作)。
另一种可能的解决方案有数千种,有人在下面发布了一种称为“单例”的设计模式。然而,该模式最近被重新评估为反模式,不应使用。
关于PHP PDO-MYSQL : How to use database connection across different classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514143/