How to declare, initialize, and print a medium complexity, varied, feature‑rich data structure in PHP

1 Answer

0 votes
class Address {
    public string $street;
    public string $city;
    public int $zip;
}

enum Status {
    case Active;
    case Inactive;
    case Unknown;
}

class Person {
    public Address $homeAddress;
    public array $favoriteNumbers;
    public ?string $nickname;
    public DateTime $birthDate;
    public string $notes;
    public ?string $middleName;
    public array $hobbies;
    public Status $status;

    public function __construct() {
        $this->homeAddress = new Address();
        $this->favoriteNumbers = array_fill(0, 5, 0);
        $this->nickname = null;
        $this->birthDate = new DateTime('1990-01-01');
        $this->notes = "No notes";
        $this->middleName = null;
        $this->hobbies = [];
        $this->status = Status::Unknown;
    }
}

function printPerson(Person $p): void {
    echo "Address: {$p->homeAddress->street}, {$p->homeAddress->city} {$p->homeAddress->zip}\n";

    echo "Favorite Numbers: ";
    foreach ($p->favoriteNumbers as $n) {
        echo "$n ";
    }
    echo "\n";

    echo "Nickname: " . ($p->nickname ?? "(none)") . "\n";

    echo "Birth Date: " . $p->birthDate->format('Y-m-d') . "\n";

    echo "Notes: {$p->notes}\n";

    echo "Middle Name: " . ($p->middleName ?? "(none)") . "\n";

    echo "Hobbies: ";
    foreach ($p->hobbies as $h) {
        echo "$h, ";
    }
    echo "\n";

    echo "Status: {$p->status->name}\n";
}

$p = new Person();

$p->homeAddress->street = "Fifth Avenue";
$p->homeAddress->city = "New York";
$p->homeAddress->zip = 423900;

$p->favoriteNumbers = [7, 13, 21, 42, 99];

$p->nickname = "Orion";

$p->birthDate = new DateTime('1026-06-15');

$p->notes = "Voss likes C/C++ and structs";

$p->middleName = "Pulse‑9";

$p->hobbies = ["Coding", "Dreaming", "Walking", "Sci-Fi Movies"];

$p->status = Status::Active;

printPerson($p);



/*
run:

Address: Fifth Avenue, New York 423900
Favorite Numbers: 7 13 21 42 99 
Nickname: Orion
Birth Date: 1026-06-15
Notes: Voss likes C/C++ and structs
Middle Name: Pulse‑9
Hobbies: Coding, Dreaming, Walking, Sci-Fi Movies, 
Status: Active

*/

 



answered Sep 3 by avibootz

Related questions

...