0
0
PHPprogramming~30 mins

Null safe operator in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Null safe operator
📖 Scenario: Imagine you have a list of people, and each person may or may not have a car. You want to check the color of each person's car safely without causing errors if the car is missing.
🎯 Goal: Build a PHP script that uses the null safe operator to safely access the car color of each person.
📋 What You'll Learn
Create a class Car with a public property color.
Create a class Person with a public property car that can be null or a Car object.
Create an array people with some Person objects, some with cars and some without.
Use the null safe operator ?-> to get the car color safely for each person.
Print the car color or "No car" if the person has no car.
💡 Why This Matters
🌍 Real World
In real applications, objects may or may not have related objects. The null safe operator helps avoid errors when accessing properties of objects that might be missing.
💼 Career
Understanding the null safe operator is important for writing clean and error-free PHP code, especially when working with APIs, databases, or complex data structures.
Progress0 / 4 steps
1
Create classes and people array
Create a class called Car with a public property color. Create a class called Person with a public property car. Then create an array called people with three Person objects: the first has a Car with color "red", the second has no car (null), and the third has a Car with color "blue".
PHP
Need a hint?

Define the classes with public properties and create the array with the exact objects and values.

2
Add a variable for the people array
Create a variable called people that holds the array of Person objects you created in Step 1.
PHP
Need a hint?

The $people variable should already be set from Step 1.

3
Use null safe operator to get car colors
Use a foreach loop with variable $person to iterate over $people. Inside the loop, create a variable $color that uses the null safe operator ?-> to get the color property of the car property of $person. If the car is missing, $color should be null.
PHP
Need a hint?

Use ?-> to safely access color from car.

4
Print car colors or 'No car'
Inside the foreach loop, print the value of $color if it is not null. Otherwise, print "No car". Use echo to display the output followed by a newline.
PHP
Need a hint?

Use the null coalescing operator ?? to print $color or "No car".