在PHP中的类中使用全局DB变量

时间:2010-12-16 08:31:23

标签: php class object global

如何在类中使用全局数据库变量? 假设我在config.php

中有这个
$dbh = new PDO("mysql:host=localhost;dbname=mydb", "root", "");

我想在内部使用这个$ dbh,如下所示(MyClass.php)

class MyClass
{
   public function DoSomething($plogin_id)
   {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
   }
}

在我的index.php文件中,我正在使用此MyClass,如下所示:

include "config.php";
$MyObject = new MyClass();
$login_result = $MyObject->DoSomething("admin");

它给了我错误:

  

致命错误:调用成员函数   prepare()在非对象上   C:\ XAMPP \ htdocs中\ MyProject的\ ADMIN \包括\类\ MyClass.php   第14行

3 个答案:

答案 0 :(得分:7)

您必须以某种方式将$dbh对象传递给MyClass。既然你不想使用全局变量,我建议你把它传递给MyClass的构造函数。

您的MyClass和index.php看起来像这样:

class MyClass
{
   protected $dbh = null;

   public function __construct ( PDO $Pdh )
   {
      $this->dbh = $Pdh;
   }

   public function DoSomething($plogin_id)
   {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $this->dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
   }
}

// in your index.php
$MyObject = new MyClass ( $dbh );

这基本上是一种称为依赖注入的模式。有关这是什么的更多信息,请参阅this excellent tutorial

答案 1 :(得分:1)

您可以使用以下方法将其引入您的函数:

global $dbh;

但是,将它添加到课程中可能更好一点,如下所示:

class MyClass
{
    private $dbh;

    public function __construct($dbh) {
        $this->dbh = $dbh;
    }

    public function DoSomething($plogin_id)
    {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $this->dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
    }
}

然后:

include "config.php";
$MyObject = new MyClass($dbh); // I'm assuming $dbh is created in config.php
$login_result = $MyObject->DoSomething("admin");

或者,在通话时将其引入您的功能:

class MyClass
{
    public function DoSomething($plogin_id, $dbh)
    {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
    }
}

然后:

include "config.php";
$MyObject = new MyClass($dbh); // I'm assuming $dbh is created in config.php
$login_result = $MyObject->DoSomething("admin", $dbh);

答案 2 :(得分:0)

这是最常用的方法:

public function DoSomething($plogin_id){
    global $dbh;
    ...

替代方法:

为数据库连接创建singleton。而你使用它而不是全局变量:

$stmt = MyDBConn::getInstance()->prepare($sql);