doukao8851 2015-02-26 01:19
浏览 19

从另一个类n php访问变量作为对象

Hello am trying to access the pdo object returned from DatabaseConnection class in Database class but its giving me difficulty am using singleton pattern .please help

class DatabaseConnection {
    protected static $_instance = NULL;
    public static $pdo;
    private function __construct() {
        try {
            $this->pdo = new PDO ( 'mysql:host=' . Configuration::getConfiguration ( 'mysql/host' ) . ';dbname=' . Configuration::getConfiguration ( 'mysql/databaseName' ), Configuration::getConfiguration ( 'mysql/user' ), Configuration::getConfiguration ( 'mysql/password' ) );
        } catch ( PDOException $e ) {
            echo 'woops !connection to the server failed.' . $e->getMessage ();
        }
    }


    public static function getConnectionInstance() {
        if (! isset ( self::$_instance )) {
            self::$_instance = new DatabaseConnection ();
        }
        return self::$_instance;
    }
}/*end od DatabaseConnection*/



class Database implements DatabaseInterface {
    public static function select($fields = array(), $table, $where = array()) 
    {
        $fields = '`' . implode ( '`,`', $fields ) . '`';
        $fix = '';
        $x = 1;
        foreach ( $where as $tableField => $value ) {
            $fix .= "`{$tableField}` = '{$value}'";
            if ($x < count ( $where )) {
                $fix .= ' AND ';
            }
            $x ++;
        }
        $sql = "SELECT {$fields} FROM `{$table}`  WHERE {$fix} ";
        if (DatabaseConnection::$pdo->prepare ( $sql )) {
            echo 'prepared';
        }
        return false;
    } 
}
  • 写回答

1条回答 默认 最新

  • dpg78570 2015-02-26 01:41
    关注

    The $pdo member should be an instance member instead of class member. Change public static $pdo to public $pdo only. Then you can access the PDO instance by

    DatabaseConnection::getConnectionInstance()->pdo;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?