Search⌘ K
AI Features

Challenge: Implementing a Class with PHP 8 Advanced OOP Features

Explore how to implement a PHP 8 class with advanced OOP features like constructor property promotion and match expressions. Learn to create and manage user data efficiently with named arguments. This lesson helps you master key PHP 8 OOP enhancements for cleaner, more effective code.

We'll cover the following...

This challenge will extensively test your understanding of the new PHP 8 OOP features. We will use these concepts to create a class to store student information.

Task

  • Create a class that contains the student’s personal information, such as gender, age, name, etc.

  • Please use constructor property promotion to create the constructor of this class.

  • Create a function that is used to display the student’s personal information.

    • Utilize the match function to add “Mr.” and “Ms.” before students’ names based on their gender.

    • Display a "Hello" message to display the personal information in the following format:

Hello Mr. Educative, you are 7 years old.
  • Please use named arguments to store data in the Student class.

Instructions

  • Implement a PHP class named User is defined. The class has a constructor method using constructor property promotion that initializes three private properties: $name, $age, and $gender.

  • The class contains a method named getInfo(), which returns a string.

  • Create an instance of the User class, which is created using named arguments in the constructor.

  • After creating the User object, the getInfo() method is called on the $user object. Display the user information depending on the value of the $gender variable.

Coding playground

Attempt the challenge in the coding playground below. Good luck!

PHP
<?php
// Write your code here
?>