返回对象中的数据解析

时间:2014-01-07 16:11:22

标签: php oop pdo

我对OOP很新,所以这可能是一个愚蠢的问题。

我有一个数据库抽象层类,如下所示:

class DB {
public static $instance = null;

private     $_pdo = null,
            $_query = null,
            $_error = false,
            $_results = null,
            $_count = 0;

private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
    } catch(PDOExeption $e) {
        die($e->getMessage());
    }
}

public static function getInstance() {
    // Already an instance of this? Return, if not, create.
    if(!isset(self::$instance)) {
        self::$instance = new DB();
    }
    return self::$instance;
}

public function query($sql, $params = array()) {

    $this->_error = false;

    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }

    return $this;
}




public function results() {
    // Return result object
    return $this->_results;
}



public function count() {
    // Return count
    return $this->_count;
}

public function error() {
    return $this->_error;
}

当我从另一个文件调用查询方法时

    $users = DB::getInstance()->query('SELECT * FROM users');
var_dump($users);

我以这种格式获取用户数据:

  

DB Object([_ pdo:DB:private] => PDO Object()[_ query:DB:private] => PDOStatement Object>([queryString] => SELECT * FROM sheild)[_ error:DB :private] => [_results:DB:private] =>>数组([0] => stdClass对象([sid] => 1 [名称] => Scutum [权重] => 55 [防御] => 90> [描述] =>罗马塔盾牌)[1] => stdClass对象([sid] => 2 [名称] =>>修改过的Scutum [weight] => ; 65 [防御] => 100 [描述] =>修改后的较重的scutum>提供更多保护)[2] => stdClass对象([sid] => 3 [name] =>圆形Parmula> ; [weight] => 30 [防御] => 60 [描述] => Thracian warrioirs使用的较小盾牌)> [3] => stdClass对象([sid] => 4 [name] = >矩形Parmula [权重] => 40 [防御]> => 75 [描述] => Scutum大小的一半)[4] => stdClass对象([sid] => 5> [name] => Hoplon [weight] => 20 [防御] => 35 [des cription] => Hoplon是佩戴在手臂上的小型圆形青铜盾牌。[5] => stdClass对象([sid] => 6 [name] => Aspis> [weight] => 35 [防御] => 50 [描述] => Hoplon的铁版本)> [_ count: DB:private] => 6)

为什么这段代码会起作用?

    foreach ($shields as $shield) {
    echo $sheild->name;
}

我错过了什么?

1 个答案:

答案 0 :(得分:1)

你有一个结果方法,使用它。我不确定你是否可以在课外迭代私有对象。

$results = $users->results();
foreach($results as $shield){
    echo $user->name;
    //your code here
}

或者在您的数据库类

中将$ this-> _result从private更改为public