2014-01-07 5 views
0

Я довольно новичок в ООП, так что это, наверное, глупый вопрос.Анализ данных в объекте

У меня есть класс слой абстракции базы данных, которая нравится так:

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] => >Array ([0] => stdClass Object ([sid] => 1 [name] => Scutum [weight] => 55 [defense] => 90 >[description] => Roman tower shield) [1] => stdClass Object ([sid] => 2 [name] => >Modified Scutum [weight] => 65 [defense] => 100 [description] => Modified heavier scutum >that provides more protection) [2] => stdClass Object ([sid] => 3 [name] => Round Parmula >[weight] => 30 [defense] => 60 [description] => smaller shield used by Thracian warrioirs) >[3] => stdClass Object ([sid] => 4 [name] => Rectangular Parmula [weight] => 40 [defense] >=> 75 [description] => Half the sized of Scutum) [4] => stdClass Object ([sid] => 5 >[name] => Hoplon [weight] => 20 [defense] => 35 [description] => The Hoplon is a small, >round bronze shield worn on the arm) [5] => stdClass Object ([sid] => 6 [name] => Aspis >[weight] => 35 [defense] => 50 [description] => Iron version of Hoplon)) >[_count:DB:private] => 6)

Зачем нужен этот код?

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

что мне не хватает?

+0

Ээээ, потому что это объект. –

+2

Я думаю, вы должны вернуть $ this -> _ results вместо $ this – bksi

+0

Lol, я знал, что это что-то в этом роде. Большое спасибо! – EnderWiggins

ответ

1

У вас есть метод результатов, используйте его. Я не уверен, что вы можете выполнять итерацию через закрытый объект вне класса.

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

или изменить $ это -> _ результат от частного к общественности в вашей БД класса

+0

Да, я использовал \t $ shields = DB :: getInstance() -> query ('SELECT * FROM sheild') -> results(); \t foreach ($ shields as $ shield) { \t \t echo $ shield-> name; \t} И это сработало! – EnderWiggins

Смежные вопросы