我想在从数据库中获取数据后立即创建一个对象。
为此,我使用pdo::fetch_类和一个重写的uu set()方法,我已经将其放入trait中。
但是,我不明白为什么我在提到:
致命错误:Uncaught ArgumentCounterRor:函数banner::\uu construct()的参数太少,传递了0,在第34行的d:\logiiels\wamp64\www\projet-4\writer blog\entity\banner.php中正好需要1个参数
这是我的横幅类(省略setters和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);
}
}
}
我的神奇方法是:
<?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!');
}
}
}
这是我的班纳曼经理的恳求,我在那里获取我的数据:
<?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;
}
最佳答案
这里的实际问题是如何对需要构造函数参数的类使用PDO::FETCH_CLASS
,错误消息就是这样说的。
答案是setFetchMode's third parameter.。
$req->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Banner',[[]]);
应该做到这一点,为构造函数提供一个空数组,从而让代码到达实际调用
__set()
的点。