0% complete

Functions · Lesson 6 of 9

Type Declarations

Declare accepted parameter and return types.

Lesson

Parameter and return types document a function contract and let PHP detect incompatible values. PHP supports scalar, class, union, nullable, and other types. Strict typing can make scalar behavior less surprising; still validate data at external boundaries because type declarations are not a substitute for domain validation. The declared return type ensures the function returns an integer result. Further guidance Treat a function as a small contract: name its inputs, state what it returns, and avoid hidden dependencies. Test a representative value and an edge case. Keep a function focused; callers should decide how to display a returned result or handle a reported failure. Practice task: Create a fresh example for Type Declarations. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Type Declarations
PHP
declare(strict_types=1);
function double(int $value): int
{
    return $value * 2;
}
echo double(6);
Expected output
12

Key points

  • Declare accepted parameter and return types.
  • Keep inputs, return values, and side effects explicit.
  • Prefer focused functions that are easy to test independently.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.