Search⌘ K

Solution: Implementing a Class with PHP 8 Advanced OOP Features

Explore how to implement a PHP 8 class utilizing advanced object-oriented programming features such as constructor property promotion, match expressions, and named arguments. Understand how these features simplify code and enhance readability while producing dynamic personalized output.

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

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