PHP PDO MySQL的:如何使用在不同类
问题描述:
我有点新的数据库连接使用MySQL的PDO,这里有我的两个文件:PHP PDO MySQL的:如何使用在不同类
我有我用来连接到数据库的连接类:
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和面向对象的东西。 在此先感谢。
答
解决方案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();
说明
作为一般好的规则:始终指定范围的关键字功能(公共,受保护或私人)。
第一种解决方案称为继承,我们基本上做的是用连接类扩展帐户类,以便继承连接类中的所有方法和属性并轻松使用它们。在这种情况下,你必须小心命名冲突。我建议你看看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(....)
等
然后他将为他的账户类的每个实例创建一个新的数据库连接(以及其他每个类这需要数据库连接)。 – Martin 2012-07-16 23:49:59
@Martin,我已经更新了我的答案 – Shoe 2012-07-16 23:58:15
好了,所以下面的最新版本,他现在需要跟踪$ con在整个应用程序范围内(并且非常小心,不要覆盖它),并将其传递给每个其他对象/明确地关闭。现在我明白为什么单身人士是一个坏主意! :) – Martin 2012-07-16 23:58:43