0
0
PHPprogramming~5 mins

Type declarations for parameters in PHP

Choose your learning style9 modes available
Introduction

Type declarations help make sure the right kind of data is given to a function. This stops mistakes and makes code easier to understand.

When you want to make sure a function only gets numbers, not words.
When you want to check that a function receives a list (array) before working on it.
When you want to avoid bugs caused by wrong data types in your code.
When you want to clearly show what kind of data a function expects.
When you want PHP to automatically check data types and give errors if wrong.
Syntax
PHP
function functionName(type $parameterName) {
    // function body
}

Type can be a built-in type like int, string, array, or a class name.

PHP will give an error if the wrong type is passed when calling the function.

Examples
This function expects a string for the $name parameter.
PHP
function greet(string $name) {
    echo "Hello, $name!";
}
This function expects two integers and returns their sum.
PHP
function add(int $a, int $b) {
    return $a + $b;
}
This function expects an array and prints each item on a new line.
PHP
function printItems(array $items) {
    foreach ($items as $item) {
        echo "$item\n";
    }
}
Sample Program

This program defines a function that multiplies two integers. It then calls the function with 4 and 5 and prints the result.

PHP
<?php
function multiply(int $x, int $y) {
    return $x * $y;
}

$result = multiply(4, 5);
echo "4 times 5 is $result";
OutputSuccess
Important Notes

If you pass the wrong type, PHP will show a TypeError.

You can also use nullable types by adding a question mark, like ?int, to allow null values.

Type declarations make your code safer and easier to read.

Summary

Type declarations tell PHP what kind of data a function expects.

This helps catch mistakes early and makes code clearer.

Use them to improve your code's quality and reliability.