Current Location: Home> Latest Articles> PHP Function Syntax Explained: Definition, Parameters, Return Type, and Practical Examples

PHP Function Syntax Explained: Definition, Parameters, Return Type, and Practical Examples

M66 2025-09-25

Overview of PHP Function Syntax

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 }

Function Body

The function body contains the code that will be executed when the function is called.

Parameters

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.

Return Type

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; }

Practical Example: Calculate String Length

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

Conclusion

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.