Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13679

Declares values on objects and output the values

I need some guide or reference on how should I do this. What I should do is, have a class structure named Cat and have a static method that outputs new object.

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;

This is the best thing that I can come up with here is the problem, they said I just used an array and not an object. I used array because I have to put the values on the $Cat so it can be passed on the parameter.

Upvotes: 0

Views: 43

Answers (2)

Ibu
Ibu

Reputation: 43810

if you want to set those values to the object here is what you do

...
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

Update:

Now i get a better idea what you are trying to do, this is how your class will look like:

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";
    }
}

now you can set your values

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

Note that $output is an object

Upvotes: 1

uzyn
uzyn

Reputation: 6683

Looks like it's an assignment on object-oriented programming concept in PHP. I believe this is what you're trying to accomplish, with comments explaining the steps.

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;

Upvotes: 1

Related Questions