我对使用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和OOP的新手。提前谢谢。
解决方案1
用class account_info extends connection {
替换class account_info {
更换
$con = new connection();
$info = new account_info();
带有
$info = new account_info();
它应该起作用。
解决方案2(建议)
在这种情况下,我强烈建议您使用依赖项注入来解决问题。只需将您的帐户类别替换为:
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)指定scope关键字。
第一个解决方案称为继承,我们基本上是用连接类扩展account类,以便从连接类继承所有方法和属性并轻松使用它们。在这种情况下,您必须注意命名冲突。我建议您看一下PHP手册中的类继承。
第二种解决方案称为依赖注入,这是一种广受欢迎的设计模式,它使您的类在其构造函数中接受其他类,以便显式定义类依赖树(在这种情况下,帐户依赖于连接,没有连接,我们就无法使帐户工作)。
成千上万种可能的解决方案中的另一种是有人在下面发布的一种,它是一种名为Singleton的设计模式。然而,该模式最近被重新评估为反模式,不应使用。
一种常见的方法是在数据库类中使用singleton
模式。
类似这样的东西:
class connection {
private static $hInstance;
public static function getInstance() {
if (!(self::$hInstance instanceof self)) {
self::$hInstance = new self();
}
return self::$hInstance;
}
/* your code */
}
然后,你可以简单地使用
$database = connection::getInstance();
$database->con->prepare(....)
etc