我是面向对象编程的新手,我无法找到为什么我的这个练习项目是错误的。它不断给我以下错误消息:
“警告:Character::__construct() 缺少参数 2,在第 26 行的 C:\Users\User\Documents\NetBeansProjects\PhpProject3\poo_bdd\connect_bdd.php 中调用并在 C:\Users\User\Documents\NetBeansProjects 中定义第 13 行的 \PhpProject3\poo_bdd\Character.class 和参数 3 到 6 相同
类的定义
<?php
class Character
{
//attributs de la classe
private $_id;
private $_name;
private $_strength;
private $_damage;
private $_level;
private $_experience;
//on définit le constructeur
public function __construct($id, $name,$strength,$damage,$level,$experience)
{
$this->setId($id);
$this->setName($name);
$this->setStrength($strength);
$this->setDamage($damage);
$this->setLevel($level);
$this->setExperience($experience);
}
//hydratation
public function hydrate(array $data)
{
foreach ($data as $key => $value)
{
$method = 'set'.ucfirst($key);
if (method_exists($this, $method))
{
$this->$method($value);
}
}
if(isset($data['id']))
{
$this->setId($data['id']);
}
if(isset($data['name']))
{
$this->setName($data['name']);
}
if(isset($data['strength']))
{
$this->setStrength($data['strength']);
}
if(isset($data['damage']))
{
$this->setDamage($data['damage']);
}
if(isset($data['level']))
{
$this->setLevel($data['level']);
}
if(isset($data['experience']))
{
$this->setExperience($data['experience']);
}
}
//on définit les getters et setters
//getters
public function getId()
{
return $this->_id;
}
public function getName()
{
return $this->_name;
}
public function getStrength()
{
return $this->_strength;
}
public function getDamage()
{
return $this->_damage;
}
public function getLevel()
{
return $this->_level;
}
public function getExperience()
{
return $this->_experience;
}
// setters
public function setId($id)
{
$this->_id = (int) $id;
}
public function setName($name)
{
if (is_string($name) && strlen($name) <= 30)
{
$this->_name = $name;
}
}
public function setStrength($strength)
{
$this->_strength = $strength;
}
public function setDamage($damage)
{
$this->_damage = $damage;
}
public function setLevel($level)
{
$this->_level = $level;
}
public function setExperience($experience)
{
$this->_experience = $experience;
}
}
?>
和PHP代码:
<?php
require ('Character.class');
try
{
//connexion à la table blog_messages
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=test; charset=UTF-8', 'root', '', $pdo_options);
$bdd->query('SET NAMES utf8');
//sélection des 3 derniers billets
$request = $bdd->query('SELECT id, name, strength, damage, level, experience FROM personnages');
//affichage des billets
while ($data = $request->fetch(PDO::FETCH_ASSOC))
{
$character = new Character($data);
echo $character->getName(),' has a strength of',$character->getStrength();
}
//on termine le traitement de la requète
$request->closeCursor();
}
catch (Exception $e)
{
die('Erreur: '.$e->getMessage());
}
?>
SQL tbale 有 6 列:id、name、strength、damage、level、experience。
如果有人有线索,那就太好了。
谢谢你的帮助!