...

/

Solution: Implementing a Class with PHP 8 Advanced OOP Features

Solution: Implementing a Class with PHP 8 Advanced OOP Features

A detailed review of the solution to the challenge involving the application of concepts to create a class for storing and extracting data using new OOP features.

We'll cover the following...

The code widget below contains the solution to the challenge. We will also go through a step-by-step explanation of the solution.

Solution

Press + to interact
<?php
class User {
public function __construct( // Constructor property promotion
private string $name,
private int $age,
private string $gender
) {}
public function getInfo(): string {
$greeting = match ($this->gender) { // Match function
'M' => 'Mr. ',
'F' => 'Ms. ',
default => ''
};
return "Hello $greeting$this->name, you are $this->age years old!";
}
}
$user = new User(name: 'John', age: 25, gender: 'M'); // Named arguments
echo $user->getInfo(); // Output: Hello Mr. John, you are 25 years old!
?>

Let’s get into the code:

  • Lines 3–7: The ...