Home >Backend Development >PHP Tutorial >How to specify parameters of PHP function? What types can they be?

How to specify parameters of PHP function? What types can they be?

WBOY
WBOYOriginal
2024-04-17 08:48:011264browse

The parameter passing methods of PHP functions include: passing by value, passing by reference and default value parameters. Parameter type checking of original and composite types is supported. In actual applications, passing by value will not affect the original value, while passing by reference will. Modify the original value, and the default value parameter provides a default value.

PHP 函数的参数如何指定?它们可以是什么类型?

Parameter specification and type of PHP function

The parameters of the function in PHP can be specified as:

Passed by value ( Default)

function sum($a, $b) {
  $a += $b;
}

Pass by reference

function increment(&$a) {
  $a++;
}

Default value

function greet($name = "World") {
  echo "Hello, $name!";
}

Parameter type

Parameter type can be:

  • Primitive type: Integer, floating point number, string, Boolean value
  • Composite Type: Array, object
  • Empty: Indicates that any type of parameter can be accepted

Example

function formatDate(DateTime $date) {
  // 对 DateTime 对象操作
}

function avg(int $a, int $b): float {
  return ($a + $b) / 2;
}

Practical case

Pass by value and pass by reference

function doubleValue($value) {
  $value *= 2;
}

$x = 10;
doubleValue($x);  // $x 不会改变,因为按值传递
echo $x;  // 输出 10

function doubleValueByRef(&$value) {
  $value *= 2;
}

doubleValueByRef($x);  // $x 已修改,因为按引用传递
echo $x;  // 输出 20

Default value and type checking

function greeting($name = "World") {
  echo "Hello, $name!";
}

greeting();  // 显示 "Hello, World!"
greeting("Alice");  // 显示 "Hello, Alice!"

The above is the detailed content of How to specify parameters of PHP function? What types can they be?. 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