[英]PHP PDO-MYSQL : How to use database connection across different classes
我对使用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 {
与class account_info extends connection {
更换
$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)指定范围关键字。
第一个解决方案称为继承,我们基本上做的是使用连接类扩展帐户类,以便从连接类继承所有方法和属性并轻松使用它们。 在这种情况下,您必须注意命名冲突。 我建议你看一下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(....)
等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.