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
matchfunction 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
Studentclass.
Instructions
Implement a PHP class named
Useris 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
Userclass, which is created using named arguments in the constructor.After creating the
Userobject, thegetInfo()method is called on the$userobject. Display the user information depending on the value of the$gendervariable.
Coding playground
Attempt the challenge in the coding playground below. Good luck!