2014-12-03 40 views
-3

的index.php意外的PHP錯誤:調用一個成員函數......一個非對象

$user = db::getInstance()->get('test', array('user_name', '=', 'rahul')); 

if ($user->count()){ 
    echo 'NO user'; 
} else { 
    echo 'Ok'; 
} 

db.php中

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; 
} 

private function action($action, $table, $where){    
    if(count($where==3)) { 

     $opertors = array('=', '<', '>', '>=', '<=');     

     $field = $where[0]; 
     $opertor = $where[1]; 
     $value = $where[2]; 

     if(in_array($opertor, $opertors)){      

      $sql = "{$action} FROM {$table} WHERE {$field} {$opertor} ?";      

      if (!$this->query($sql, array($value))->error()){ 
       echo ' Go it'; 
       return $this ; 
      } 
     } 
    } 

    return false; 
} 

public function get($table, $where){ 
    return $this->action('SELECT *', $table, $where); 
} 

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

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

我得到這個錯誤:

Fatal error: Call to a member function count() on a non-object in C:\wamp\www\ooplr\index.php on line 10

我錯過了什麼?

+0

嘗試轉儲$ user,看看裏面有什麼 – Matheno 2014-12-03 11:58:25

+0

'var_dump($ user)'give ...? – 2014-12-03 11:58:38

+0

它給'布爾假'....... – 2014-12-03 12:00:32

回答

1

您應該檢查是否db::getInstance()->get成功返回的對象。以下行:

if ($user->count()){ 

失敗,因爲$user不是這裏的對象。代碼如下:

$user = db::getInstance()->get('test', array('user_name', '=', 'rahul')); 
if(!$user) { 
    echo 'EVERYTHING GOES WRONG'; 
} else { 
    // OK, PROCESSING 
} 
+0

沒有朋友....這裏沒有問題...... 它適用於當我使用db :: getInstance() - >查詢(「SELECT * FROM test WHERE user_name = ?「,array('rahul)); – 2014-12-03 12:13:02

+0

**有時**這個'get'可能會失敗,並且您必須**每次檢查返回**的內容**之後再調用'$ user- > count()'。 – mudasobwa 2014-12-03 12:14:47

+0

if(!$ this-> query($ sql,array($ value)) - > error()) 如果語句正在執行false,則給出的條件.... 不知道怎麼做? – 2014-12-03 12:22:04

2

試試這個,

if(count($where)==3){ 
       ^^ 

,而不是

if(count($where==3)){ 
+0

同樣的錯誤:( – 2014-12-03 12:03:38

相關問題