Hello again, dedicated PHP learners!
Functions in PHP are blocks of statements that can be used repeatedly in a program. They allow for better organization, reusability, and readability. A function will execute when it is “called” from another point in the script.
In this module, we’ll uncover the nuances of defining, calling functions, handling parameters, and return values. Let’s step into the world of functions!
Defining and Calling Functions
In PHP, a function is defined using the function keyword, followed by a user-defined name for the function:
function greet() {
echo "Hello from the function!";
}
To execute a function, you simply call it by its name:
greet(); // Outputs: Hello from the function!
Parameters
Functions can accept parameters, which are specified after the function name, inside parentheses. You can add as many parameters as you like, just separate them with a comma:
function greetPerson($name) {
echo "Hello, " . $name . "!";
}
greetPerson("Zahwah"); // Outputs: Hello, Zahwah!
Return Values
A function can return a value using the return statement. The return value can be any type:
function addNumbers($num1, $num2) {
return $num1 + $num2;
}
$result = addNumbers(5, 3);
echo $result; // Outputs: 8
When a function returns a value, it can be used in expressions:
echo addNumbers(5, 3) * 2; // Outputs: 16
Exercise
It’s your turn to put the knowledge into practice:
- Create a function named calculateArea that accepts the length and width of a rectangle as parameters and returns its area.
- Call the function with different values and display the results.
Conclusion
Fantastic! You’ve taken another pivotal step in your PHP journey by understanding the power and flexibility of functions. Functions are the building blocks of scalable and maintainable code.
As you continue your path in PHP, remember to use functions to keep your code DRY (Don’t Repeat Yourself) and organized.