猿问

创建的类有错误。帮助找到它,请)

我正在学习 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";

    } 

?>


慕森王
浏览 148回答 3
3回答

有只小跳蛙

任务说如果年龄超出范围,您应该将其设置为字符串unset。打电话unset($w)不会那样做。将其更改为:$w&nbsp;=&nbsp;"unset";

胡子哥哥

你很接近。将变量、参数和参数命名为有意义的名称。如果它大于 130 或小于 0,则将 $age 值设置为未设置(就像字符串一样)大概意思 $this->age = 'unset';<?php&nbsp;class User{&nbsp; &nbsp; private $name;&nbsp; &nbsp; private $age;&nbsp; &nbsp; public $site;&nbsp; &nbsp; function __construct($name, $site, $age)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo "User was successfully created!";&nbsp; &nbsp; &nbsp; &nbsp; $this->name = $name;&nbsp; &nbsp; &nbsp; &nbsp; $this->site = $site;&nbsp; &nbsp; &nbsp; &nbsp; if ($age > 130 || $age < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->age = 'unset';&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->age = $age;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public function getFullInfo()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return "$this->name at the age of $this->age is a user of $this->site";&nbsp; &nbsp; }}$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

紫衣仙女

我认为这里是:&nbsp;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;希望能帮助到你
随时随地看视频慕课网APP
我要回答