Bird
Raised Fist0
PHPprogramming~10 mins

Nullable types in functions in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Nullable types in functions
Function Declaration
↓
Parameter Type: Nullable
↓
Function Call with Value
↓
Function Executes Normally
↓
Function Call with null
↓
Function Accepts null Without Error
↓
Return or Output
The function declares a parameter that can be a type or null. When called, it accepts either a value of that type or null, allowing flexible inputs.
Execution Sample
PHP
<?php
declare(strict_types=1);
function greet(?string $name) {
  if ($name === null) {
    return "Hello, Guest!";
  }
  return "Hello, $name!";
}

echo greet("Alice");
echo greet(null);
This function greets a person by name or says 'Hello, Guest!' if null is passed.
Execution Table
StepFunction CallParameter $nameCondition $name === nullReturn ValueOutput
1greet("Alice")"Alice"False"Hello, Alice!""Hello, Alice!"
2greet(null)nullTrue"Hello, Guest!""Hello, Guest!"
3End---No more calls
💡 No more function calls; execution ends.
Variable Tracker
VariableStartAfter Call 1After Call 2Final
$name-"Alice"nullnull or string
Key Moments - 2 Insights
Why can the function accept null even though the parameter type is string?
Because the parameter is declared as ?string, which means it can be a string or null, as shown in execution_table row 2 where $name is null and accepted.
What happens if we pass a non-string and non-null value?
PHP will throw a TypeError because the parameter expects either a string or null, not other types. This is not shown in the table but is important to remember.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the return value when greet(null) is called?
A"Hello, Guest!"
B"Hello, null!"
Cnull
DError
💡 Hint
Check execution_table row 2 under 'Return Value'
At which step does the condition $name === null evaluate to True?
AStep 1
BStep 3
CStep 2
DNever
💡 Hint
Look at the 'Condition $name === null' column in execution_table
If we remove the question mark from ?string in the function parameter, what would happen when calling greet(null)?
AFunction returns "Hello, Guest!"
BPHP throws a TypeError
CFunction returns "Hello, null!"
DFunction treats null as empty string
💡 Hint
Nullable types allow null; removing ? disallows null, causing error on null input
Concept Snapshot
Nullable types in PHP functions:
- Use ? before type to allow null (e.g., ?string)
- Function accepts value of type or null
- Check for null inside function to handle special cases
- Passing null without ? causes TypeError
- Enables flexible and safe function inputs
Full Transcript
This example shows a PHP function greet with a nullable string parameter. The question mark before string means the parameter can be a string or null. When calling greet with "Alice", the function returns "Hello, Alice!". When calling greet with null, the function returns "Hello, Guest!" because it checks if the parameter is null. This allows the function to handle missing or optional names safely. If the question mark is removed, passing null would cause an error. This trace helps understand how nullable types work in PHP functions.

Practice

(1/5)
1. What does a nullable type declaration like ?int mean in a PHP function parameter?
easy
A. The parameter is optional and defaults to zero.
B. The parameter can be either an integer or null.
C. The parameter can be any type except integer.
D. The parameter must always be an integer, never null.

Solution

  1. Step 1: Understand nullable type syntax

    The ? before int means the parameter can accept null or an int value.
  2. Step 2: Interpret the meaning in function parameters

    This allows the function to safely accept missing or empty values represented by null.
  3. Final Answer:

    The parameter can be either an integer or null. -> Option B
  4. Quick Check:

    Nullable type = int or null [OK]
Hint: Nullable means type or null allowed, check for ? before type [OK]
Common Mistakes:
  • Thinking nullable means optional parameter
  • Assuming nullable excludes null values
  • Confusing nullable with default values
2. Which of the following is the correct nullable type syntax to declare a function parameter that accepts a nullable string in PHP?
easy
A. function greet(string? $name) {}
B. function greet(string|null $name) {}
C. function greet(?string $name) {}
D. function greet($name?: string) {}

Solution

  1. Step 1: Recall nullable type syntax in PHP

    Nullable types use a question mark ? before the type, like ?string.
  2. Step 2: Check each option's syntax

    function greet(?string $name) {} uses ?string correctly. function greet(string|null $name) {} uses union type syntax which is valid in PHP 8+, but the question asks for nullable syntax specifically. Options C and D are invalid syntax.
  3. Final Answer:

    function greet(?string $name) {} -> Option C
  4. Quick Check:

    Nullable syntax = ?type before parameter [OK]
Hint: Use ? before type for nullable, not after or inside parentheses [OK]
Common Mistakes:
  • Placing ? after the type name
  • Using union type syntax instead of nullable syntax
  • Misplacing the question mark in parameter
3. What will be the output of this PHP code?
function checkAge(?int $age) {
    if ($age === null) {
        return "Age not provided";
    }
    return "Age is $age";
}

echo checkAge(null);
medium
A. Age not provided
B. Age is
C. Error: Argument must be int
D. Age is null

Solution

  1. Step 1: Understand nullable parameter and null check

    The function accepts an ?int, so null is allowed. It checks if $age === null and returns "Age not provided".
  2. Step 2: Call the function with null

    Calling checkAge(null) triggers the null check, so it returns "Age not provided".
  3. Final Answer:

    Age not provided -> Option A
  4. Quick Check:

    Nullable param null input returns null check message [OK]
Hint: Check for null explicitly when using nullable types [OK]
Common Mistakes:
  • Assuming null converts to empty string
  • Expecting type error on null input
  • Ignoring strict null check with ===
4. Identify the error in this PHP function declaration:
function setName(?string name) {
    echo $name;
}
medium
A. Missing dollar sign ($) before parameter name.
B. Nullable types cannot be used with strings.
C. Function must return a value.
D. Parameter cannot be nullable without default value.

Solution

  1. Step 1: Check parameter syntax

    In PHP, all variable names must start with a dollar sign $. The parameter name is missing $.
  2. Step 2: Validate nullable type usage

    Nullable types like ?string are valid. The function does not require a return value. Parameters can be nullable without default values.
  3. Final Answer:

    Missing dollar sign ($) before parameter name. -> Option A
  4. Quick Check:

    Parameter variables need $ prefix [OK]
Hint: Always prefix parameter names with $ in PHP functions [OK]
Common Mistakes:
  • Omitting $ in parameter names
  • Thinking nullable types need default values
  • Expecting functions must return values
5. You want to write a PHP function that accepts a nullable float and returns its square if given, or returns 0 if null. Which of the following implementations is correct?
hard
A. function square(?float $num): float { return $num * $num; }
B. function square(?float $num): ?float { return $num ? $num * $num : 0; }
C. function square(float $num = null): float { return $num * $num; }
D. function square(?float $num): float { if ($num === null) { return 0; } return $num ** 2; }

Solution

  1. Step 1: Check nullable parameter and return type

    The function accepts ?float and returns float. It must handle null safely and return a float.
  2. Step 2: Analyze each option's logic

    function square(?float $num): float { return $num * $num; } does not check for null and will cause an error if $num is null. function square(?float $num): float { if ($num === null) { return 0; } return $num ** 2; } checks for null explicitly and returns 0, then squares the number correctly. function square(float $num = null): float { return $num * $num; } uses default null but parameter is not nullable, causing a type error. function square(?float $num): ?float { return $num ? $num * $num : 0; } returns nullable float but uses a loose check $num ? which fails for 0.0 (falsey), so it returns 0 incorrectly.
  3. Final Answer:

    function square(?float $num): float { if ($num === null) { return 0; } return $num ** 2; } -> Option D
  4. Quick Check:

    Check null explicitly, return float, use strict null check [OK]
Hint: Always check null explicitly before math with nullable types [OK]
Common Mistakes:
  • Not checking for null before calculation
  • Using loose truthy checks that fail on 0.0
  • Mismatching return types with nullable parameters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard