Home >Backend Development >PHP Tutorial >How to specify parameters of PHP function? What types can they be?
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.
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:
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!