2014-02-23 109 views
0
class User{ 
public $id, $username, $firstname, $lastname; 

public function find(){ 
$result = blabla->query('SELECT * FROM users WHERE id = 1'); 
return $result; 
} 
} 

我很感興趣的是如何將值(來自mysql)賦值給類變量。PHP OOP爲類變量賦值

$user = new User(); 
$user->find(); 
echo $user->username; 
echo $user->lastname; 

回答

0

我不知道這是否會與SELECT *工作,但你可以嘗試PDO::FETCH_INTO

class User{ 
    public $id, $username, $firstname, $lastname; 
    public function find(){ 
     $result = blabla->query('SELECT id, username, firstname, lastname FROM users WHERE id = 1'); 
     $this = $result->fetch(PDO::FETCH_INTO); 
    } 
} 

如果它不工作,你可以使用bindColumn call with PDO::FETCH_BOUND選項:

class User{ 
    public $id, $username, $firstname, $lastname; 
    public function find() { 
     $result = blabla->query('SELECT id, username, firstname, lastname FROM users WHERE id = 1'); 
     $result->bindColumn(1, $this->id); 
     /* Other bindColumn calls here */ 
     return $result->fetch(PDO::FETCH_BOUND); 
    } 
} 
0

你可以嘗試這樣做:

class User{ 
    public $id, $username, $firstname, $lastname; 
    public function find() { 
     $result = blabla->query('SELECT * FROM users WHERE id = 1'); 

     $this->id = $result['id']; 
     $this->username = $result['username']; 
     $this->firstname = $result['firstname']; 
     $this->lastname = $result['lastname']; 
    } 
}