0
0
PHPprogramming~5 mins

Nullable types in functions in PHP

Choose your learning style9 modes available
Introduction

Nullable types let a function accept either a specific type or null. This helps when a value might be missing or optional.

When a function parameter can be a number or no value at all.
When a function should return a string or nothing (null).
When you want to clearly say a value can be empty or a certain type.
When working with optional settings or inputs in your code.
Syntax
PHP
function functionName(?TypeName $param): ?ReturnType {
    // function body
}

The ? before a type means it can be that type or null.

You can use nullable types for both parameters and return values.

Examples
This function accepts a string or null. It greets a guest if no name is given.
PHP
<?php
function greet(?string $name): void {
    if ($name === null) {
        echo "Hello, guest!\n";
    } else {
        echo "Hello, $name!\n";
    }
}
This function returns a string username or null if not found.
PHP
<?php
function findUser(int $id): ?string {
    if ($id === 1) {
        return "Alice";
    }
    return null;
}
Sample Program

This program shows how a function uses a nullable integer parameter to describe age or say it's unknown.

PHP
<?php
function describeAge(?int $age): string {
    if ($age === null) {
        return "Age is unknown.";
    }
    return "Age is $age years.";
}

echo describeAge(25) . "\n";
echo describeAge(null) . "\n";
OutputSuccess
Important Notes

Nullable types help avoid errors when values might be missing.

Remember to check for null inside the function before using the value.

Summary

Nullable types allow null or a specific type in functions.

Use ? before the type to make it nullable.

Check for null inside your function to handle missing values safely.