There are four ways to call functions in PHP: regular calls, parameter passing, return values and variable functions. Regular calls use function names and parameters; parameter passing can be by value or by reference; return values use the return keyword; variable functions use the variable name as the function name.
In PHP, functions can be called in the following four ways:
The most basic function calling method is:
function_name(arg1, arg2, ...);
For example:
echo hello(); // 输出:"Hello"
Function parameters can be passed by value or by reference:
Pass by reference by adding &
symbols in front of the parameter name, for example:
function swap(&$a, &$b) { $temp = $a; $a = $b; $b = $temp; } $a = 1; $b = 2; swap($a, $b); echo "$a, $b"; // 输出:"2, 1"
The function can return A value, use the return
keyword, for example:
function double(int $num): int { return $num * 2; } echo double(5); // 输出:"10"
The variable function is a special function calling method in PHP, which allows the variable name to be used as a function name. The syntax is as follows:
$function_name($arg1, $arg2, ...);
For example:
<?php $hello = "Hello"; $hello("World!"); // 等同于 echo "Hello World!"; ?>
Example: Calculate the average of two numbers
<?php function average(int $num1, int $num2): float { return ($num1 + $num2) / 2; } // 调用函数 echo "两数的平均值为:" . average(5, 10) . "\n"; // 输出:"7.5" ?>
Passed With the function calling method introduced above, we can flexibly use PHP functions to complete various programming tasks.
The above is the detailed content of How to call PHP functions?. For more information, please follow other related articles on the PHP Chinese website!