Current Location: Home> Latest Articles> Comprehensive Guide to Defining and Calling Functions in PHP

Comprehensive Guide to Defining and Calling Functions in PHP

M66 2025-07-10

Definition and Role of Functions in PHP

In PHP programming, a function is a reusable block of code. Proper use of functions enhances code clarity and strengthens modularity and maintainability. This article will introduce how to define and call functions in PHP with illustrative examples.

How to Define a Function

Functions in PHP are defined using the function keyword. The basic syntax is as follows:

function functionName(parameters) {
    // function body code
}

Here, functionName is the function's name and can be customized as needed; parameters represent the list of function parameters and can be empty or include one or more parameters.

For example, the following defines a function that calculates the sum of two numbers:

function sum($num1, $num2) {
    $result = $num1 + $num2;
    return $result;
}

In this case, the function sum takes two parameters $num1 and $num2, and returns their sum.

How to Call a Function

To call a function, simply use the function name followed by the arguments in parentheses. The syntax is:

<span class="fun">functionName(arguments);</span>

The example below calls the previously defined sum function:

$num1 = 10;
$num2 = 20;
$total = sum($num1, $num2);
echo $total;

Here, two variables $num1 and $num2 are defined, then the sum function is called to calculate their sum, and the result is output.

Complete Example of Function Definition and Call

The following demonstrates a more complete example defining a function to calculate the product of two numbers and calling it:

// Define function: calculate the product of two numbers
function multiply($num1, $num2) {
    $result = $num1 * $num2;
    return $result;
}

// Call the function
$num1 = 5;
$num2 = 2;
$product = multiply($num1, $num2);
echo "The product of the two numbers is: " . $product;

In this example, the multiply function calculates the product of its two parameters. After calling it, the result is stored in $product and printed.

Summary

This article introduced the basics of defining and calling functions in PHP with code examples to aid understanding. Functions are fundamental for code reuse, improving program structure and maintainability. Mastering function usage is an essential step in learning PHP. We hope this content is helpful for beginners.