我想从数据库中获取数据后立即创建一个对象。
为此,我使用的是PDO :: FETCH_CLASS和重写的__set()方法(已将其放入特征中)。
但是,我不知道为什么我提到了一个错误: “致命错误:未捕获的ArgumentCountError:函数Banner :: __ construct()的参数太少,传递了0个参数,并且在D:\ Logiciels \ wamp64 \ www \ projet-4 \ writer-blog \ entity \ Banner.php中正好期望了1个参数34“
这是我的Banner类(省略了setter和getter):
<?php
require_once(__DIR__.'\Set.php');
/**
* This class represents a banner that will be displayed on the homepage of the FrontEnd
*/
class Banner
{
use Set;
protected $errors=[],
$id,
$displayOrder,
$title,
$caption,
$image,
$buttonTitle,
$buttonLink,
$creationDate,
$modificationDate;
/**
* Constants for errors management during the execution of the methods
*/
const INCORRECT_IMAGE_LINK = 1;
const INCORRECT_TITLE = 2;
const INCORRECT_CAPTION = 3;
/**
* Class constructor which assign values that have been passed in parameters to matching attributes
*
* @param array $donnees The values to allocate
* @return void
*/
public function __construct(array $data)
{
$this->hydrate($data);
}
/**
* Method that allocates specified valued to the matching attributes
*
* @param array $donnees The values to allocate
* @return void
*/
public function hydrate($data)
{
foreach ($data as $key => $value)
{
$method = 'set'.ucfirst($key);
if (method_exists($this, $method))
{
$this->$method($value);
}
}
}
我的神奇方法__set()在以下特征中:
<?php
trait Set {
public function __set($property, $value)
{
$explodedProperty = explode("_", $property);
for ($i = 1 ; $i < count($explodedProperty); $i++) {
ucfirst($explodedProperty[$i]);
}
$rightPropertyName = ucfirst(implode($explodedProperty));
if (property_exists(__CLASS__, $rightPropertyName))
{
$this->$rightPropertyName = $value;
}
else
{
throw new Exception('La propriété n\'a pas pu se voir assigner une valeur car elle n\'existe pas!');
}
}
}
这是我提取数据的BannerManager的开头:
<?php
require_once("model/Manager.php");
require_once("entity/Banner.php");
class BannerManager extends Manager
{
public function getBanners()
{
$db = $this->dbConnect();
$req = $db->query('SELECT id, title, caption, image, button_title, button_link,
DATE_FORMAT(creation_date, \'%d/%m/%Y à %Hh%imin%ss\') AS creation_date_fr, DATE_FORMAT(modification_date, \'%d/%m/%Y à %Hh%imin%ss\') AS modification_date_fr
FROM banners ORDER BY display_order LIMIT 5');
$req->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Banner');
$banners = $req->fetchAll();
return $banners;
}
答案 0 :(得分:1)
您真正的问题是如何在需要构造函数参数的类中使用PDO::FETCH_CLASS
,因为错误消息就是这样。
答案是setFetchMode's third parameter.。
$req->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Banner',[[]]);
应该可以解决,为构造函数提供一个空数组,从而使您的代码到达实际调用__set()
的地步。