声明对象上的值并输出这些值


Declares values on objects and output the values

我需要一些关于如何做到这一点的指导或参考。我应该做的是,有一个名为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上,这样它才能传递到参数上。

看起来这是对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;

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

...
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="meow";$age="12";$string="'test','sample','help'";$Cat=数组($name,$age,$string);$output=Cat::ToData($Cat);echo$output;

注意,$output是一个对象