gpt4 book ai didi

php - PDO 使用 PDO::FETCH_PROPS_LATE 和 __construct() 调用?

转载 作者:可可西里 更新时间:2023-11-01 00:10:27 25 4
gpt4 key购买 nike

我正在尝试创建一个新的 Setting 对象实例,调用 __construct() 方法,使用 PHP PDO 并约束 PDO::FETCH_PROPS_LATE。不幸的是,我收到此警告(并且绑定(bind)不起作用)。

如何将列值传递给构造方法?

Warning: Missing argument 1 for Setting::__construct() in pdo.php.

Notice: Undefined variable: key in pdo.php.

class Setting
{

protected $key, $value, $displayable;

public function __construct($key, $value = null, $displayable = 1)
{
$this->key = $key;
$this->value = $value;
$this->displayable = $displayable > 0;
}

}

while($mashup = current($mashups))
{
$stmt = $dbh->prepare('SELECT `key`, value, displayable
FROM setting WHERE mashup_id = :id');

$stmt->bindParam(':id', $mashup->id, PDO::PARAM_INT);
$stmt->execute();

$settings = $stmt->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,
'Setting');
}

$stmt->closeCursor();

最佳答案

您的构造函数中有一个非默认参数 $key:

public function __construct($key, $value = null, $displayable = 1)

所以,当你这样做的时候:

$settings = $stmt->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,'Setting');

错误:警告:缺少参数 1 for Setting::__construct() in pdo.php 仅针对参数 $key 抛出,因为它不是默认值。

fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,...的正确使用是这样的:

$variable = $stmt->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,
'classname',
<array of parameter names(in order) used in constructor>);

因此,在您的情况下:

$variable = $stmt->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,
'Setting',
array('key', 'value', 'displayable');

关于php - PDO 使用 PDO::FETCH_PROPS_LATE 和 __construct() 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9127693/

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