我想使用 PDO 的 FETCH_INTO 的构造函数填充类:
I want to populate class with constructor using FETCH_INTO of PDO:
class user
{
private $db;
private $name;
function __construct($id)
{
$this->db = ...;
$q = $this->db->prepare("SELECT name FROM users WHERE id = ?");
$q->setFetchMode(PDO::FETCH_INTO, $this);
$q->execute(array($id));
echo $this->name;
}
}
这不起作用.没有错误,只是没有.脚本没有错误,FETCH_ASSOC 工作正常.
This does not work. No error, just nothing. Script has no errors, FETCH_ASSOC works fine.
FETCH_INTO 有什么问题?
您的代码中有两个错误:
You have two errors in your code:
1) 你忘记了 $q->fetch()
1) You forgot $q->fetch()
...
$q->execute(array($id));
$q->fetch(); // This line is required
2) 但即使在添加 $q->fetch() 之后你也会得到这个:
2) But even after adding $q->fetch() you'll get this:
致命错误:无法访问私有属性 User::$name in ...
Fatal error: Cannot access private property User::$name in ...
因此,如您所见,即使在类方法内部调用 PDO,它也无法访问私有成员.
So, as you can see, PDO cannot access private members even if it is called inside class method.
这是我的解决方案:
...
$q->execute(array($id));
$q->setFetchMode(PDO::FETCH_ASSOC);
$data = $q->fetch();
foreach ($data as $propName => $propValue)
{
// here you can add check if class property exists if you don't want to
// add another properties with public visibility
$this->{$propName} = $propValue;
}
这篇关于PDO 的 FETCH_INTO $这个类不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
MySQLi准备好的语句&foreach 循环MySQLi prepared statement amp; foreach loop(MySQLi准备好的语句amp;foreach 循环)
mysqli_insert_id() 是从整个服务器还是从同一用户获Is mysqli_insert_id() gets record from whole server or from same user?(mysqli_insert_id() 是从整个服务器还是从同一用户获取记录?)
PHP MySQLi 无法识别登录信息PHP MySQLi doesn#39;t recognize login info(PHP MySQLi 无法识别登录信息)
mysqli_select_db() 需要 2 个参数mysqli_select_db() expects exactly 2 parameters(mysqli_select_db() 需要 2 个参数)
Php mysql pdo 查询:用查询结果填充变量Php mysql pdo query: fill up variable with query result(Php mysql pdo 查询:用查询结果填充变量)
MySQLI 28000/1045 用户“root"@“localhost"的访问MySQLI 28000/1045 Access denied for user #39;root#39;@#39;localhost#39;(MySQLI 28000/1045 用户“root@“localhost的访问被拒绝)