PHP:在类中使用数据库

时间:2013-12-19 21:53:10

标签: php mysql database class pdo

我已经有一个数据库文件,当我包含它时连接到数据库

类database.php中

class dbFactory {
    private static $host    = 'some.host.com';
    private static $name    = 'someDB';
    private static $user    = 'someUser';
    private static $pass    = 'somePassword';


    public function __construct() { }


    public static function pdo() {
        try {
            # MySQL with PDO_MYSQL
            return new PDO("mysql:host=$host;dbname=$name", $user, $pass);
            }
        catch(PDOException $e) {
            echo $e->getMessage();
            return null;
            exit;
            }  
    } // End: pdo()
} //End class

我通常通过以下方式访问:

require( 'some-file-path' . 'class-database.php' );
$db = dbFactory::pdo();

以下是问题: 如何从其他课程中访问$db

例如,如果我在该类中有一个名为class-html.php的类文件(AKA,作为类代码的一部分),我需要像......这样的东西:

类html.php

class html {
  ...some code...
  $db->query('SELECT * FROM tbl_head');
  ...some more code...
} //End: html

我一直在做的没有成功的是:

require( 'some-file-path' . 'class-database.php' );
$db = dbFactory::pdo();

require( 'some-file-path' . 'class-html.php' );

我收到错误消息,不知道该怎么做

2 个答案:

答案 0 :(得分:2)

您可以使用Singleton class

class dbFactory {

    //...
    private static $pdo_instance = null;

    private static function getPDOinstance() {
        if (self::$pdo_instance === null) {
            try {
                self::$pdo_instance = new PDO("...");
            } catch (PDOException $e) {
                //...
            }
        }
        return self::$pdo_instance;
    }

}

当您现在访问dbFactory::getPDOinstance()时,您将只有一个PDO实例,使用数据库在每个类中创建新的

答案 1 :(得分:1)

您的class-html.php内的课程可以按照以下几行进行修改:

require( 'some-file-path' . 'class-database.php' );

class SomeClass {
  public $db;

  def __construct() {
    $db = dbFactory::getPDOinstance();
    // existing code ..
  }

  // other code      
}

然后,您可以像往常一样要求课程:

require( 'some-file-path' . 'class-html.php' );
$obj = new SomeClass();
$obj->db->query('SELECT * FROM tbl_head')

更新:如果您多次实例化SomeClass,这将创建一个新的PDO实例。
更新:使用kingkero的答案来代替使用现有的dbFactory实例。

相关问题