gpt4 book ai didi

PHP OOP 为类变量赋值

转载 作者:行者123 更新时间:2023-11-30 00:38:29 25 4
gpt4 key购买 nike

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 OOP 为类变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21973844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com