【问题标题】:Warning: Missing argument 1 for Personnage::__construct()警告: Personnage::__construct() 缺少参数 1
【发布时间】:2016-07-28 11:20:46
【问题描述】:

我的代码收到以下错误。请帮帮我。

警告:缺少 Personnage::__construct() 的参数 1,调用 public_html/PooEnPhp/index.php 在第 24 行并定义在 public_html/PooEnPhp/Personnage.class.php 在第 22 行

类文件: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;
    }

Personnage 类的实例化文件: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(); 

通常在 index.php 中,我应该能够使用隐含的默认构造函数 __construct() 来实例化 Personnage 类。

但是我收到了上面的错误。谁能解释一下为什么?

谢谢

【问题讨论】:

    标签: php constructor


    【解决方案1】:

    问题出在这里:

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

    ?>

    这基本上设置了参数的默认值,因此可以不提供它们。

    【讨论】:

    • 它有效。按照您的回答向构造函数提供默认值后。谢谢。
    【解决方案2】:

    因为构造函数需要两个参数:

    public function __construct($force, $degats) {
    

    并且您无需任何参数即可调用它:

    $perso = new Personnage(); 
    

    【讨论】:

      【解决方案3】:

      您已经定义了一个带有两个参数的构造函数,这意味着您需要在实例化它时提供这些参数,例如:

      $perso = new Personnage($force, $degats); 
      

      【讨论】:

        猜你喜欢
        • 2017-05-05
        • 2014-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-14
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        相关资源
        最近更新 更多