In PHP, functions are reusable code blocks that allow you to encapsulate code and call it multiple times as needed. The basic syntax for a PHP function is as follows:
function function_name(parameter1, parameter2, ...) { // Function body }
The function body contains the code that will be executed when the function is called.
Functions can accept multiple parameters, which are passed within the parentheses of the function definition, separated by commas. These parameters provide input data to the function.
PHP allows you to specify a return type when defining a function, which indicates the type of value that the function will return. For example, the following code defines a function that returns an integer:
function get_sum(int $num1, int $num2): int { return $num1 + $num2; }
In this practical example, we will define a function to calculate the length of a string.
function get_string_length(string $string): int { return strlen($string); }
Now, let's call the function and output the result:
$string = "Hello World"; echo get_string_length($string); // Outputs 11
This article covered the basic syntax of PHP functions, including function definition, parameter passing, and the use of return types. Hopefully, these examples and explanations will help you better understand the basics of using PHP functions.