0
0
PHPprogramming~15 mins

Nullable types in functions in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Nullable types in functions
📖 Scenario: You are building a simple PHP program that handles user profiles. Sometimes, the user may not provide their middle name, so your function should accept a nullable string for the middle name.
🎯 Goal: Create a PHP function that accepts a nullable string parameter for the middle name and returns a greeting message that includes the middle name if provided, or a default message if not.
📋 What You'll Learn
Create a function called greetUser that accepts a nullable string parameter called $middleName
Inside the function, check if $middleName is null
Return a greeting message that includes the middle name if it is not null
Return a different greeting message if $middleName is null
Call the function twice: once with a middle name and once with null
Print the results of both function calls
💡 Why This Matters
🌍 Real World
Nullable types are common when dealing with optional user input, like middle names or phone numbers, where the value might be missing.
💼 Career
Understanding nullable types helps you write safer PHP functions that handle missing or optional data without errors.
Progress0 / 4 steps
1
Create the function with a nullable parameter
Write a PHP function called greetUser that accepts one parameter ?string $middleName. The function should start with an empty body.
PHP
Need a hint?

Use ?string before the parameter name to make it nullable.

2
Add a variable for the default message
Inside the greetUser function, create a variable called $defaultMessage and set it to the string 'Hello, guest!'.
PHP
Need a hint?

Assign the string 'Hello, guest!' to the variable $defaultMessage.

3
Add logic to return greeting based on nullable parameter
Inside the greetUser function, write an if statement to check if $middleName is not null. If it is not null, return the string 'Hello, ' . $middleName . '!'. Otherwise, return the $defaultMessage.
PHP
Need a hint?

Use if ($middleName !== null) to check if the parameter has a value.

4
Call the function and print the results
Call the greetUser function twice: once with the argument 'James' and once with null. Print both results using echo with a newline after each.
PHP
Need a hint?

Use echo to print the returned strings with a newline "\n" after each.