无法在类php

时间:2016-10-31 10:31:50

标签: php

我现在正在使用代码学院网站学习php,但有些没有正确解释。

以下是条件:

  1. 创建一个名为Cat的课程。
  2. 向此类添加两个公共属性:$isAlive应存储值true$numLegs应包含值4.
  3. 添加公开$name属性,该属性通过__construct()或。
  4. 获取其值
  5. 添加名为meow()的公共方法,该方法返回"喵喵"。
  6. 创建Cat类的实例,其中包含$name" CodeCat"。
  7. 调用此Cat上的meow()方法并回显结果。
  8. 这是创建的代码:

    <!DOCTYPE html>
    <html>
        <head>
          <title> Challenge Time! </title>
          <link type='text/css' rel='stylesheet' href='style.css'/>
        </head>
        <body>
          <p>
            <?php
              // Your code here
              class Cat {
                 public $isAlive = true;
                 public $numLegs = 4;
                 public $name ;
    
                  public function __construct() {
                      $cat->name = $name;;
                      }
                  public function meow(){
                      return "Meow meow";
                      }
                  }
    
    
                  $cat = new Cat(true ,4 , CodeCat);
                  echo $cat->meow();
            ?>
          </p>
        </body>
    </html>   
    

2 个答案:

答案 0 :(得分:2)

有三个错误:

  1. __没有参数的构造函数
  2. 在构造函数中使用未定义的变量$cat而不是 $this
  3. CodeCat应为字符串'CodeCat'
  4. 工作代码应如下所示:

    <?php
              // Your code here
              class Cat {
                 public $isAlive = true;
                 public $numLegs = 4;
                 public $name ;
    
                  public function __construct($isAlive,$numLegs,$name) {
                      $this->name = $name;
                      $this->isAlive = $isAlive;
                      $this->numLegs = $numLegs;
                      }
                  public function meow(){
                      return "Meow meow";
                      }
                  }
    
    
                  $cat = new Cat(true ,4 , 'CodeCat');
                  echo $cat->meow();
            ?>
    

答案 1 :(得分:0)

在您的代码中,您有一个没有参数的构造函数,因此$name将是未定义的。当你想创建一个新对象Cat时,你用3个参数调用它,但是你没有这样的构造函数。

你想要的是一个带有1个参数$name的构造函数,并用这个参数调用它:

<?php
      // Your code here
      class Cat {
         public $isAlive = true;
         public $numLegs = 4;
         public $name ;

         public function __construct($name) {
              $this->name = $name;
         }
         public function meow(){
              return $this->name;
         }
      }


      $cat = new Cat('CodeCat');  //Like this you will set the name of the cat to CodeCat
      echo $cat->meow();  //This will echo CodeCat
?>
相关问题