Reputation: 93
I am receiving following error for my code. Please help me out.
Warning: Missing argument 1 for Personnage::__construct(), called in public_html/PooEnPhp/index.php on line 24 and defined in public_html/PooEnPhp/Personnage.class.php on line 22
Class file : Personnage.class.php
<?php
class Personnage {
private $_force = 20;
private $_localisation = 'Lyon';
private $_experience = 0;
private $_degats = 0;
// Create a connstructor with two arguments
public function __construct($force, $degats) {
echo 'Voici le constructeur ! ';
$this->_force = $force;
$this->_degats = $degats;
}
The file instantiating the Personnage class: index.php
<?php
function chargerClasse($classe) {
require $classe . '.class.php';
}
//autoload the function chargerClasse
spl_autoload_register('chargerClasse');
// instantiate the Personnage class using the default constructor (the one implied without argument)
$perso = new Personnage();
Normally in index.php I should be able to instanciate the the Personnage class using the implied default constructor __construct().
But I am getting the error above. Can somebody explain me why ?
Thanks
Upvotes: 1
Views: 4790
Reputation: 553
The problem is in here:
// Create a connstructor with two arguments
public function __construct($force, $degats) {
echo 'Voici le constructeur ! ';
$this->_force = $force;
$this->_degats = $degats;
}
The $force
and $degates
are both set as obligatory parameters.
To be able to call new Personnage()
with setting any parameters you have to change your class to this:
<?php
class Personnage {
private $_force = 20;
private $_localisation = 'Lyon';
private $_experience = 0;
private $_degats = 0;
// Create a connstructor with two arguments
public function __construct($force = 20, $degats = 0) {
echo 'Voici le constructeur ! ';
$this->_force = $force;
$this->_degats = $degats;
}
}
?>
This basically sets default values for the parameters so it will be ok not to supply them.
Upvotes: 2
Reputation: 7150
You've defined a constructor that takes two arguments whch means you need to supply those args when instantiating it, e.g.:
$perso = new Personnage($force, $degats);
Upvotes: 0
Reputation: 69460
because the constructor expect two arguments:
public function __construct($force, $degats) {
and you call it without any Argument:
$perso = new Personnage();
Upvotes: 0