2016-07-28 4 views
1

私のコードに次のエラーがあります。私を助けてください。警告:Personnage :: __ construct()の引き数1がありません

警告:Personnageための欠落引数1 :: __構築物()、ライン24上 のpublic_html/PooEnPhp/index.phpの中で呼ばれ、ライン22

に のpublic_html/PooEnPhp/Personnage.class.phpで定義されています

クラスファイル:Personnage.class.php Personnageクラスをインスタンス化

<?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; 
    } 

ファイル:

index.phpを10
<?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(); 

通常、index.phpには、暗黙のデフォルトコンストラクタ__construct()を使用してPersonnageクラスをインスタンス化できる必要があります。

しかし、上記のエラーが発生しています。誰かがなぜ私を説明することができますか?

おかげ

答えて

2

問題はここにある:

// Create a connstructor with two arguments 
public function __construct($force, $degats) { 
    echo 'Voici le constructeur ! '; 
    $this->_force = $force; 
    $this->_degats = $degats; 
} 
$force

$degatesは、両方の必須のパラメータとして設定されています。 はこれにあなたのクラスを変更するためにあなたが持っている任意のパラメータを設定してnew Personnage()を呼び出すことができるようにするには:

<?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; 
    } 
} 

>

それらを供給しないようにOKになりますので、これは基本的にパラメータのデフォルト値を設定します? 。

+0

これは機能します。あなたが答えたときにコンストラクタにデフォルト値を与えた後。ありがとうございました。 –

0

コンストラクタは二つの引数を期待するので:

public function __construct($force, $degats) { 

を、あなたは任意の引数なしでそれを呼び出す:

$perso = new Personnage(); 
0

あなたは手段whch二つの引数を取るコンストラクタを定義しましたインスタンス化するときにこれらの引数を指定する必要があります。例:

$perso = new Personnage($force, $degats); 
関連する問題