Adrian
Adrian

Reputation: 399

User Class In OOP

I was started my learing in OOP and I make a class but I have a problem now. This is my little code:

class User {

    public $name;
    public $age;
    public $city;

    public function setDate($setName, $setAge, $setCity) 
    {
        $this->name = $setName;
        $this->age = $setAge;
        $this->city = $setCity;
    }

    public function pullDate()
    {
        return $this->name;
        return $this->age;
        return $this->city;
    }

}

$newUser = new User;
$newUser->setDate('Adrian', '23', 'Poland');
echo $newUser->pullDate();

And when I get variable by echo $newUser->pullDate(); in response recerive only 'Adrian' ... How I can fix it?

Thanks for help!

Upvotes: 0

Views: 404

Answers (1)

arkascha
arkascha

Reputation: 42925

A function can only return a single value. Placing multiple return statements in a row does not make any sense, the function will always return after the first such statement. Instead you have to combine the values, for example by creating an array out of them.

Take a look at this modified version, assuming that you are using php:

<?php 
class User {

    public $name;
    public $age;
    public $city;

    public function setDate($setName, $setAge, $setCity) 
    {
        $this->name = $setName;
        $this->age = $setAge;
        $this->city = $setCity;
    }

    public function pullDate() {
        return [
            'name' => $this->name,
            'age' => $this->age,
            'city' => $this->city
        ];
    }
}

$newUser = new User;
$newUser->setDate('Adrian', '23', 'Poland');
$userValues = $newUser->pullDate();
echo sprintf(
    "Name: %s, Age: %s, City: %s\n",
    $userValues['name'],
    $userValues['age'],
    $userValues['city']
);

An alternative would be to implement separate "getters" for each property:

class User {
    // ...
    public function getName() {
        return $this->name;
    }
    public function getAge() {
        return $this->age;
    }
    public function getCity() {
        return $this->city;
    }
    // ...
}

And then get the attributes one by one, just as desired, for example by doing:

echo sprintf(
    "Name: %s, Age: %s, City: %s\n",
    $newUser->getName(),
    $newUser->getAge(),
    $newUser->getCity()
);

Upvotes: 1

Related Questions