settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Students - PHP Classes and Objects Task

+3 votes

Define a class Student, which holds the following information about students:

  • first name
  • last name
  • age
  • hometown

Read list of students until you receive "end" command. After that, you will receive a city name. Print only students which are from the given city, in the following format: "{firstName} {lastName} is {age} years old.".

Examples:

students php classes and objects task

Hints:

  • Define a class Student with the following fields: firstName, lastName, age and city.
  • Read a list of students.
  • Read a city name and print only students which are from the given city.
asked in PHP category by user andrew

1 Answer

+2 votes

Here is my solution with getters and setters:

<?php

class Student
{
    private $firstName;
    private $lastName;
    private $age;
    private $city;

    /**
     * @param mixed $firstName
     */
    public function setFirstName($firstName): void {
        $this->firstName = $firstName;
    }

    /**
     * @param mixed $lastName
     */
    public function setLastName($lastName): void {
        $this->lastName = $lastName;
    }

    /**
     * @param mixed $age
     */
    public function setAge($age): void {
        $this->age = $age;
    }

    /**
     * @param mixed $city
     */
    public function setCity($city): void {
        $this->city = $city;
    }

    /**
     * @return mixed
     */
    public function getFirstName() {
        return $this->firstName;
    }

    /**
     * @return mixed
     */
    public function getLastName() {
        return $this->lastName;
    }

    /**
     * @return mixed
     */
    public function getAge() {
        return $this->age;
    }

    /**
     * @return mixed
     */
    public function getCity() {
        return $this->city;
    }
}

$command = readline();
$students = [];

while ($command !== "end") {
    $fields = explode(" ", $command);

    $newStudent = new Student();
    $newStudent->setFirstName($fields[0]);
    $newStudent->setLastName($fields[1]);
    $newStudent->setAge($fields[2]);
    $newStudent->setCity($fields[3]);

    $students[] = $newStudent;

    $command = readline();
}

$city = readline();

foreach ($students as $student) {
    if ($city == $student->getCity()) {
        echo $student->getFirstName() . " " .
            $student->getLastName() . " is " .
            $student->getAge() . " years old." .
            PHP_EOL;
    }
}
answered by user hues
edited by user hues
...