Home  >  Article  >  Backend Development  >  How do PHP functions get parameters?

How do PHP functions get parameters?

王林
王林Original
2024-04-10 17:15:01430browse

There are two ways for PHP functions to receive parameters: passing by value or passing by reference. Pass by value passes a copy to the function, and changes to the copy will not affect the original value; pass by reference passes the reference to the function, and changes to the copy will affect the original value. Function parameters can have default values.

PHP 函数如何获取参数?

PHP function gets parameters

In PHP, functions can receive data through parameters. Parameters can be passed to functions by value or by reference.

Pass parameters by value

When you pass parameters by value, a copy of the parameter is passed to the function. Any changes made to the copy will not affect the original value.

Syntax:

function myFunction($param) {
  $param = '新的值';
}

Pass parameters by reference

When you pass parameters by reference, a reference to the parameter is passed to the function. Changes to the copy also affect the original value.

Syntax:

function myFunction(&$param) {
  $param = '新的值';
}

Default parameter values

By default, the parameters of a function have no default values. However, you can declare parameters with default values:

function myFunction($param = '默认值') {
  // ...
}

Practical example

The following function receives a parameter and multiplies it by 2:

function multiplyByTwo($num) {
  return $num * 2;
}

$result = multiplyByTwo(5); // 返回 10

In this example, the variable $num is passed by value to the multiplyByTwo function. Therefore, changes to $num will not affect the original value.

The above is the detailed content of How do PHP functions get parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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