Bird
Raised Fist0
PHPprogramming~15 mins

Nullable types in functions in PHP - Deep Dive

Choose your learning style10 modes available
Overview - Nullable types in functions
What is it?
Nullable types in functions allow a function parameter or return value to accept either a specific type or null. This means you can explicitly say a value can be, for example, an integer or nothing at all. It helps make your code clearer about when a value might be missing or optional. Nullable types are written by adding a question mark before the type name.
Why it matters
Without nullable types, developers often use unclear ways to handle missing values, like special numbers or empty strings, which can cause bugs and confusion. Nullable types make it clear when a value can be absent, improving code safety and readability. This clarity helps prevent errors and makes it easier to maintain and understand code, especially in larger projects.
Where it fits
Before learning nullable types, you should understand basic PHP types and function declarations. After nullable types, you can explore union types and strict typing for even more precise code. Nullable types are a step towards writing safer and more expressive PHP functions.
Mental Model
Core Idea
Nullable types let a function accept or return either a specific type or no value (null), making optional or missing data explicit.
Think of it like...
It's like a parking spot that can hold a car of a certain size or be empty; the spot is designed to accept either a car or nothing at all.
Function Parameter or Return Type
┌─────────────────────────────┐
│ ?Type means:                │
│ ┌───────────────┐           │
│ │ Specific Type │ or null   │
│ └───────────────┘           │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationBasic PHP function types
🤔
Concept: Functions can specify the type of their parameters and return values.
Result
5
Understanding how to declare types in functions is the foundation for using nullable types later.
2
FoundationWhat is null in PHP?
🤔
Concept: Null represents the absence of a value in PHP.
Result
No value here
Knowing what null means helps you understand why nullable types are useful.
3
IntermediateDeclaring nullable parameters
🤔Before reading on: do you think adding a question mark before a type allows null values or changes the type itself? Commit to your answer.
Concept: Adding a question mark before a type in a function parameter means it can accept that type or null.
Result
Hello, Alice! Hello, guest!
Knowing that ?string means string or null helps you write functions that handle optional inputs clearly.
4
IntermediateNullable return types
🤔Before reading on: do you think nullable return types allow returning null only, or both null and the declared type? Commit to your answer.
Concept: Functions can declare that they return either a specific type or null by using a question mark before the return type.
'Alice', 2 => 'Bob']; return $users[$id] ?? null; } echo findUser(1); // Alice echo findUser(3); // (prints nothing because null) ?>
Result
Alice
Understanding nullable return types helps you signal when a function might not find or produce a value.
5
IntermediateNullable types with default null values
🤔
Concept: You can combine nullable types with default null parameters to make arguments optional.
Result
Welcome, guest! Welcome, John!
Using nullable types with default null values makes your functions flexible and clear about optional inputs.
6
AdvancedNullable types and strict typing
🤔Before reading on: do you think nullable types behave differently when strict typing is enabled? Commit to your answer.
Concept: Nullable types work with PHP's strict typing mode to enforce type safety while allowing null values.
Result
Age is 25 Age not provided
Knowing how nullable types interact with strict typing helps prevent subtle bugs and enforces clear contracts.
7
ExpertNullable types and type coercion surprises
🤔Before reading on: do you think PHP automatically converts null to other types when nullable types are declared? Commit to your answer.
Concept: PHP may coerce null to other types in weak typing mode, which can cause unexpected behavior even with nullable types.
Result
NULL
Understanding PHP's type coercion nuances prevents bugs when using nullable types in weak typing mode.
Under the Hood
When PHP runs a function with nullable types, it checks if the value is either null or matches the declared type. This check happens at runtime if strict typing is enabled, otherwise PHP may try to convert values. Nullable types are implemented by allowing the internal type check to accept null as a valid value alongside the declared type.
Why designed this way?
Nullable types were introduced to make code more explicit and safer by clearly showing when null is allowed. Before nullable types, developers used loose conventions that led to bugs. The question mark syntax was chosen for its simplicity and clarity, fitting PHP's gradual typing approach.
Function Call
┌───────────────┐
│ Input Value   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Type Check    │
│ ?Type means:  │
│ Accept null or│
│ the Type      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Function Body │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does declaring a nullable type mean the function always returns null? Commit to yes or no.
Common Belief:If a function has a nullable return type, it always returns null sometimes.
Tap to reveal reality
Reality:Nullable return types mean the function can return null, but it doesn't have to; it may always return a value of the declared type.
Why it matters:Assuming nullable means always null can cause unnecessary checks or misunderstandings about function behavior.
Quick: Can you pass any type to a nullable typed parameter? Commit to yes or no.
Common Belief:Nullable types accept any type because null is allowed.
Tap to reveal reality
Reality:Nullable types accept only the declared type or null, not any type.
Why it matters:Passing wrong types leads to runtime errors, so understanding this prevents bugs.
Quick: Does adding a question mark before a type change the type to a new type? Commit to yes or no.
Common Belief:The question mark creates a new type different from the original.
Tap to reveal reality
Reality:The question mark only allows null in addition to the original type; it does not create a new type.
Why it matters:Misunderstanding this can confuse type declarations and lead to incorrect assumptions about type behavior.
Quick: In weak typing mode, does nullable type declaration prevent type coercion? Commit to yes or no.
Common Belief:Nullable types stop PHP from converting other types to the declared type.
Tap to reveal reality
Reality:In weak typing mode, PHP may still coerce values like empty strings to integers even with nullable types.
Why it matters:Relying on nullable types alone for type safety can cause subtle bugs if strict typing is not enabled.
Expert Zone
1
Nullable types combined with union types allow very flexible and precise function signatures.
2
In PHP 8.1+, readonly properties can be nullable, adding complexity to object immutability.
3
Nullable types interact with PHP's type variance rules, affecting inheritance and interface implementation.
When NOT to use
Avoid nullable types when a value should never be missing; instead, use exceptions or default values. For multiple possible types, prefer union types over nullable types alone.
Production Patterns
Nullable types are commonly used for optional parameters, database fields that may be missing, and functions that may not find a result. They improve API clarity and reduce bugs by making nullability explicit.
Connections
Optional parameters
Nullable types often work with optional parameters to allow missing arguments.
Understanding nullable types clarifies how optional parameters can be typed safely and explicitly.
Union types
Nullable types are a special case of union types combining a type with null.
Knowing nullable types helps grasp the broader concept of union types for flexible typing.
Database NULL values
Nullable types in PHP correspond to NULL values in databases representing missing data.
Recognizing this connection helps developers handle data consistently between PHP code and databases.
Common Pitfalls
#1Passing a wrong type to a nullable parameter causes runtime errors.
Wrong approach:
Correct approach:
Root cause:Misunderstanding that nullable means any type is allowed, not just the declared type or null.
#2Assuming nullable return type means function can return any type or null.
Wrong approach:
Correct approach:
Root cause:Confusing nullable with allowing any type instead of the declared type or null.
#3Using nullable types without strict typing enabled, expecting strict type checks.
Wrong approach:
Correct approach:
Root cause:Not enabling strict typing leads to unexpected type coercion despite nullable declarations.
Key Takeaways
Nullable types explicitly allow a function parameter or return value to be a specific type or null, improving code clarity.
They are declared by adding a question mark before the type, like ?int or ?string.
Nullable types help handle optional or missing data safely and clearly in PHP functions.
Understanding nullable types prevents common bugs related to unexpected null or wrong types.
Using nullable types with strict typing enabled ensures the best type safety and predictable behavior.

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