class User{
public $id, $username, $firstname, $lastname;

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


我对如何将值(来自mysql)分配给类变量很感兴趣。

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

最佳答案

我不确定它是否可以与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 );
    }
}

关于php - PHP OOP将值分配给类变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21973844/

10-09 04:15