[英]cannot define constant in class php
我现在正在使用代码学院网站学习php,但其中一些解释不正确。
这些是条件:
Cat
的类。 $isAlive
应该存储值true
而$numLegs
应该包含值4。 $name
属性,该属性通过__construct()
或获取。 meow()
的公共方法,该方法返回“ Meow meow”。 Cat
类的实例,该实例的$name
为$name
CodeCat。 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>
有三个错误:
$cat
代替$this
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.