Home > Backend Development > PHP Tutorial > What is the difference between formal parameters and actual parameters of a PHP function?

What is the difference between formal parameters and actual parameters of a PHP function?

王林
Release: 2024-04-11 10:45:02
Original
1026 people have browsed it

In PHP functions, formal parameters are placeholders when the function is defined, representing the data to be received, and actual parameters are the actual data passed to the formal parameters when the function is called. Formal parameters can specify types and default values, and actual parameters can be passed positionally or by name.

PHP 函数的形参和实参有何区别?

Formal parameters and actual parameters of PHP functions: in-depth understanding

Formal parameters and actual parameters

In PHP functions, formal parameters (parameters) are placeholders specified when defining the function and are used to receive the data actually passed to the function. Argument is the data passed to the formal parameter when the function is actually called.

Types and default values ​​of formal parameters

Formal parameters can specify a type (such as integer, string) or a default value. If no default value is specified, the variable's type is mixed, which means it can receive any type of data. For example:

function add($num1, $num2 = 0) {
  // ...
}
Copy after login

Passing actual parameters

Parameters can be passed to functions by position or by name:

  • By position Passing: The actual parameters are in the same order as the formal parameters.
  • Pass by name: Use formal parameter names as keys and pass actual parameters as values.

For example:

$result = add(10, 20); // 按位置传递
$result = add(num2: 20, num1: 10); // 按名称传递
Copy after login

Practical case: Calculate the area of ​​a circle

<?php
function calculateAreaCircle($radius) {
  return pi() * $radius ** 2;
}

$radius = 5;
$area = calculateAreaCircle($radius);

echo "圆的面积为:$area";
?>
Copy after login

Summary

  • Formal parameters are used to define placeholders for data received by the function, and actual parameters are the data actually passed to the function.
  • Formal parameters can specify types and default values.
  • Actual parameters can be passed positionally or by name.

The above is the detailed content of What is the difference between formal parameters and actual parameters of a PHP function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template