繁体   English   中英

无法在类php中定义常量

[英]cannot define constant in class php

我现在正在使用代码学院网站学习php,但其中一些解释不正确。

这些是条件:

  1. 创建一个名为Cat的类。
  2. 向此类添加两个公共属性: $isAlive应该存储值true$numLegs应该包含值4。
  3. 添加一个公共的$name属性,该属性通过__construct()或获取。
  4. 添加一个名为meow()的公共方法,该方法返回“ Meow meow”。
  5. 创建Cat类的实例,该实例的$name$name CodeCat。
  6. 在此Cat上调用meow()方法并回显结果。

这是创建的代码:

<!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>   

有三个错误:

  1. __没有参数的构造函数
  2. 在构造函数中使用未定义的$cat代替$this
  3. CodeCat应该是字符串'CodeCat'

工作代码应如下所示:

<?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();
        ?>

在您的代码中,您有一个没有参数的构造函数,因此$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
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM