Parameterized functions
Parameterized functions in PHP refer to functions that accept parameters (also known as arguments). Parameters are values that you can pass to a function when you call it, allowing the function to perform operations with those values. Here's an example of a parameterized function in PHP:
Examples:
<?php // Parameterized function that takes two numbers and returns their sum function addNumbers($num1, $num2) { $sum = $num1 + $num2; return $sum; } // Call the function with arguments 5 and 10 $result = addNumbers(5, 10); // Output the result echo "The sum is: " . $result; ?>
Output:
The sum is: 15
Explanation:
- function addNumbers($num1, $num2): This line defines a PHP function named addNumbers that takes two parameters, $num1 and $num2.
- Inside the function, $sum = $num1 + $num2; calculates the sum of the two numbers.
- return $sum;: This line returns the calculated sum from the function.
- $result = addNumbers(5, 10);: This line calls (invokes) the addNumbers function with the arguments 5 and 10.
- The function calculates the sum (5 + 10) and returns the result, which is then stored in the variable $result.
- echo "The sum is: " . $result;: Finally, this line uses the echo statement to output the string "The sum is: " concatenated with the value of $result. The output will be "The sum is: 15".
You can define functions with any number of parameters, and the parameters can have default values.
Example:
<?php
// Parameterized function with a default value
function greetUser($name = "Guest") {
echo "Hello, $name!";
}
// Call the function without providing a specific name
greetUser(); // Outputs: Hello, Guest!
// Call the function with a specific name
greetUser("John"); // Outputs: Hello, John!
?>
Output:
Hello, Guest!
Hello, John!
Explanation:
- function greetUser($name = "Guest"): This line defines a PHP function named greetUser. It has a single parameter $name with a default value of "Guest". If a value for $name is not provided when calling the function, it defaults to "Guest".
- echo "Hello, $name!";: This line inside the function uses the echo statement to output a greeting message that includes the value of the $name parameter.
- greetUser();: This line calls the greetUser function without providing a specific name. Since no value is provided for $name, the default value "Guest" is used. The output will be: Hello, Guest!
- greetUser("John");: This line calls the greetUser function with the specific name "John". The provided value for $name overrides the default value. The output will be: Hello, John!