Understanding PHP Function Parameter Passing: Pass-by-Value, Pass-by-Reference, Default and Variable‑Length Arguments
This article explains PHP function parameter passing, covering pass‑by‑value versus pass‑by‑reference, how to define functions with multiple, default, and variable‑length arguments, and provides clear code examples illustrating each technique for backend developers.
PHP is widely used for backend development, and understanding how function parameters are passed is essential. This article details the two main passing methods—pass‑by‑value, which copies the argument, and pass‑by‑reference, which passes the argument’s memory address.
<code>function addOne($a){
$a++;
}
function addOneRef(&$a){
$a++;
}
$num = 1;
addOne($num);
echo $num; // outputs 1 because the original value is unchanged
addOneRef($num);
echo $num; // outputs 2 because the original value is modified</code>When a function needs several inputs, PHP allows multiple parameters to be defined and passed in order. The position of each argument must match the corresponding parameter.
<code>function calculate($a, $b, $c){
return ($a + $b) * $c;
}
echo calculate(1, 2, 3); // outputs 9</code>Default parameters let a function assign a predefined value to a parameter if the caller omits it.
<code>function welcome($name, $age = 18){
echo "欢迎你,$name,你今年$age岁了!";
}
welcome("小明"); // 输出:欢迎你,小明,你今年18岁了!
welcome("小华", 20); // 输出:欢迎你,小华,你今年20岁了!</code>For situations where the number of arguments is unknown, PHP provides variable‑length arguments using func_get_args() and func_num_args() .
<code>function sum(){
$result = 0;
$args = func_get_args(); // retrieve all arguments
$count = func_num_args(); // number of arguments
for($i = 0; $i < $count; $i++){
$result += $args[$i];
}
return $result;
}
echo sum(1, 2, 3, 4); // outputs 10</code>In practice, developers should choose the appropriate passing method based on the specific use case, using default values and variable‑length arguments when they simplify the API, while being mindful of performance and potential side‑effects of passing by reference.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.