php
  1. php-parameterized-function

PHP Parameterized Function

A Parameterized Function is a type of function in PHP that accepts parameters or arguments while being called and can be customized according to the needs of the application. These functions take input from the user and then modify these inputs according to a specific set of instructions written within the function.

Syntax

function functionName($parameter1, $parameter2, ...){
    // Function body
}
  • functionName is the user-defined name of the function.
  • $parameter1, $parameter2, etc. are the parameters that can be used within the function.

Example

Let's take an example of a parameterized function that adds two numbers passed as parameters:

function addNumbers($number1, $number2){
    $sum = $number1 + $number2;
    return $sum;
}

$result = addNumbers(5, 7);

Output

The above example will output 12.

Explanation

In the above example, we define a function addNumbers that accepts two parameters $number1 and $number2. The function body performs the addition of $number1 and $number2 and stores the result in $sum. The result is then returned using the return keyword.

We call the function with parameters 5 and 7. The function returns the sum of 5 and 7, i.e. 12. The returned value is assigned to $result.

Use

Parameterized Functions are useful when you need to perform the same set of instructions multiple times with different inputs. They help in making the code reusable and modular.

Important Points

  • A parameterized function can accept zero or more parameters.
  • The parameters must be separated by commas in the function definition.
  • The function call must provide arguments for all the parameters defined in the function definition.
  • The data type of the parameters can be explicitly defined, but it is optional.
  • A function can have both parameterized and non-parameterized versions, depending on the use case.

Summary

In this tutorial, we learned about Parameterized Functions in PHP. We saw how to define and call a parameterized function and learned about its syntax, example, output, explanation, use, important points, and summary. Using parameterized functions makes PHP code more readable, reusable, and efficient.

Published on: