我正在学习php,其中一个任务是创建一个特定的类。我已经尝试了很多,但仍然有错误。
任务:
创建类
User
,它将具有$name
和$age
私有属性和公共$site
属性,这些值应该在类构造函数中设置,方法getFullInfo()
,这将返回(而不是打印!$this->name at the age of $this->age is a user of $this->site
.构造函数应检查输入年龄,如果它大于130
或小于0
$age
值设置为unset
(仅作为字符串(。成功创建实例后,构造函数应打印User was successfully created!
.
我使用PHP 5。
我学习的网站不应用我的解决方案版本。希望你能帮助我^^
<?php
class User{
private $name;
private $age;
public $site;
function __construct($q,$w,$e){
echo "User was successfully created!";
$this->name=$q;
$this->site=$e;
if($w>130 || $w<0){
unset($w);
};
$this->age=$w;
}
public function getFullInfo(){
return "$this->name at the age of $this->age is a user of $this->site";
}
}
?>
该任务说,如果年龄超出范围,则应将其设置为字符串unset
。打电话给unset($w)
不会这样做。将其更改为:
$w = "unset";
你很接近。将变量、参数和参数命名为有意义的名称。
如果大于 130 或小于 0,则将$age值设置为未设置(仅 作为字符串(
可能意味着$this->age = 'unset';
<?php
class User
{
private $name;
private $age;
public $site;
function __construct($name, $site, $age)
{
echo "User was successfully created!";
$this->name = $name;
$this->site = $site;
if ($age > 130 || $age < 0) {
$this->age = 'unset';
} else {
$this->age = $age;
}
}
public function getFullInfo()
{
return "$this->name at the age of $this->age is a user of $this->site";
}
}
$user = new User('Tony McTony', 'Tree House', 35);
echo $user->getFullInfo();
// Output: User was successfully created!Tony McTony at the age of 35 is a user of Tree House
<</div>
div class="one_answers">我认为在这里:
return "$this->name at the age of $this->age is a user of $this->site";
// it should be : (i think)
return $this->name . "at the age of " . $this->age . " is a user of " . $this->site;
希望对你有帮助
您的问题很可能是取消设置$w
变量。当他们说取消设置变量时,您应该对$this->age
而不是$w
这样做。
<?php
$this->age = $w;
if($w > 130 || $w < 0){
$this->age = 'unset';
};
?>
如果这不能解决您的问题,那么对问题的更具描述性的解释会有所帮助。