0

我需要一些关于如何执行此操作的指南或参考。我应该做的是,有一个名为 Cat 的类结构,并有一个输出新对象的静态方法。

class Cat{
    public $name;
    public $age;
    public $string;

    static public function ToData($Cat) {
        $input = "";
        foreach ($Cat as $key => $value) {
            $input .= "object: " . $key . "</br>";
        }
        return $input;
    }
}

$name = "meow";
$age = "12";
$string = "'test', 'sample', 'help'";
$Cat = array($name, $age);
$output = Cat::ToData($Cat);
echo $output;

这是我能想到的最好的事情就是问题,他们说我只使用了一个数组而不是一个对象。我使用数组是因为我必须将值放在 $Cat 上,以便可以将其传递给参数。

4

2 回答 2

1

看起来这是一个关于 PHP 中面向对象编程概念的作业。我相信这就是您要完成的工作,并附有解释步骤的评论。

class Cat{
    public $name;
    public $age;

    // Output the attributes of Cat in a string
    public function ToData() {
        $input = "";
        $input .= "object: name :".": ".$this->name." </br>";
        $input .= "object: age :".": ".$this->age." </br>";
        return $input;
    }
}

$name = "meow";
$age = "12";

// Instantiate Cat
$Cat = new Cat();
$Cat->name = $name;
$Cat->age = $age;

// Output Cat's attributes
$output = $Cat->ToData();
echo $output;
于 2012-07-26T05:38:08.803 回答
1

如果您想将这些值设置为对象,这就是您要做的

...
foreach ($Cat as $key => $value) {
    $this->$key = $value;
}
...

$name = "meow";
$age = "12";
$Cat = array("name"=>$name,"age"=> $age);

$cat = new Cat();
$cat->toData($Cat);

echo $cat->name;
// meow

更新

现在我对您要做什么有了更好的了解,这就是您的班级的样子:

class Cat{
    public $name;
    public $age;
    public $string;

    static public function ToData($Cat) {
        $obj = new self();
        $obj->name = $Cat["name"];
        $obj->age  = $Cate["age"];
        $obj->string  = $Cate["string"];
        return $obj;
    }

    // echo 
    public function __toString(){
       return "$this->name - $this->age - $this->string";
    }
}

现在你可以设置你的价值观

$name = "喵喵"; $年龄=“12”;$string = "'测试', '样本', '帮助'"; $Cat = 数组($name, $age,$string); $output = Cat::ToData($Cat); 回声$输出;

注意这$output是一个对象

于 2012-07-26T05:33:17.990 回答