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

时间:2015-02-26 01:19:24

标签: php mysql pdo

您好我正在尝试访问从Database类中的DatabaseConnection类返回的pdo对象,但是我使用单例模式时遇到了困难。请帮助

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 个答案:

答案 0 :(得分:0)

$pdo成员应该是实例成员,而不是成员。仅将public static $pdo更改为public $pdo。然后,您可以通过

访问PDO实例
DatabaseConnection::getConnectionInstance()->pdo;