我正在尝试使用:
$stmt>setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,static::MODEL_CLASS);
$customer = $stmt->fetch();`
将数据绑定回与static :: MODEL_CLASS关联的构造函数。即使我只是键入实际的类名“ Customer”,我在这里也会出现错误。在代码有机会获取之前,它会出错。没有setFetchMode,我会取回数据。数据库和模型以完全相同的顺序具有完全相同的属性。有人知道发生了什么吗?
错误:
(!)致命错误:未捕获的ArgumentCountError:实参太少 函数Klant :: __ construct(),传递了0,而恰好是8 D:\ Documents \ Stack \ Dropbox \ Dropbox \ Deltion \ working \ Hoofdstuk 第14行的6 \ datamapperdesignpattern.php
class Klant {
public $ID;
public $voornaam;
public $achternaam;
public $adres;
public $postcode;
public $woonplaats;
public $email;
public $password;
public function __construct($ID, $voornaam, $achternaam, $adres, $postcode, $woonplaats, $email, $password) {
$this->ID = $ID;
$this->voornaam = $voornaam;
$this->achternaam = $achternaam;
$this->adres = $adres;
$this->postcode = $postcode;
$this->woonplaats = $woonplaats;
$this->email = $email;
$this->password = $password;
}
function read($ID)
{
$stmt = $this->pdo->prepare("SELECT * FROM customer WHERE ID = ?");
try {
$stmt->bindParam(1, $ID);
$stmt->execute();
}
catch(PDOException $e) {
echo $e;
}
$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,static::MODEL_CLASS);
$customer = $stmt->fetch();
return $customer;
}
^完整代码供参考。构造函数是普通的public function __construct()
重要吗?注意: 相同的代码和数据库也可以与其他人一起使用。我重新安装了Xampp。而PHP版本是7.2.11。
答案 0 :(得分:1)
PDO不会将参数发送到构造函数。相反,您可以创建对象,然后使用PDO::FETCH_INTO
保存到已经存在的对象中。
<?php
function read($ID)
{
$stmt = $this->pdo->prepare("SELECT * FROM customer WHERE ID = ?");
try {
$stmt->bindParam(1, $ID);
$stmt->execute();
}
catch(PDOException $e) {
echo $e;
}
$customer = new Klant(...pass your desired arguments...);
$stmt->setFetchMode(PDO::FETCH_INTO, $customer);
$stmt->fetch();
return $customer;
}