【问题标题】:Declares values on objects and output the values声明对象的值并输出值
【发布时间】:2012-07-26 05:16:49
【问题描述】:

我需要一些关于如何执行此操作的指南或参考。 我应该做的是,有一个名为 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 oop object properties methods


    【解决方案1】:

    看起来这是一篇关于 PHP 中面向对象编程概念的作业。我相信这就是您要完成的任务,cmets 会解释这些步骤。

    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;
    

    【讨论】:

    • 这就是我要说的。你也可以检查我的更新。因为我想用不同的属性输出它。字符串 1、字符串 2、字符串 3。字符串="'测试','样本','帮助'"。
    • 你应该可以使用我给你的例子添加$string你自己。与$name$age 相同。至少做一点自己的功课。 :)
    • 哈哈,我真的明白了。也许我应该把整件事和我的问题放在这里。我只是害怕有人会用stackoverflow抓住我。 :) 我现在很绝望。我会更新上面的代码。
    【解决方案2】:

    如果您想将这些值设置为对象,您可以这样做

    ...
    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 是一个对象

    【讨论】:

    • 是的,但它在阵列上。我希望它在具有其属性的对象中。
    • 是的,谢谢。你也可以检查我的更新。这就是我的难题。字符串="'测试','样本','帮助'"。我还想用不同的属性输出它。字符串 1,字符串 2,字符串 3。
    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2021-07-17
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多