PHP Function Parameters
In this page:
What are Parameters?
Parameters are the named placeholders listed inside a function's parentheses when you define it. When you later *call* the function, the arguments you supply fill those placeholders in order, giving the function's body something concrete to work with.
Example: What are Parameters?
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("Alice");
?>
Login to try C/C++/Java/PHP code in the editor
Pass by Value
By default, PHP copies an argument's value into the function — any changes made to the parameter inside the function body stay local and never touch the original variable back where the function was called. This is why plain function calls can't accidentally mutate a variable you pass in.
Example: Pass by Value
<?php
function addOne($num) {
$num = $num + 1;
echo "Inside: $num\n";
}
$x = 5;
addOne($x);
echo "Outside: $x";
?>
Login to try C/C++/Java/PHP code in the editor
Pass by Reference
Prefixing a parameter name with & in the function definition switches it to pass-by-reference: the function now operates on the original variable itself, so any change it makes is visible back at the call site once the function returns — the opposite of the default copy behavior.
Example: Pass by Reference
<?php
function addOne(&$num) {
$num = $num + 1;
}
$x = 5;
addOne($x);
echo $x;
?>
Login to try C/C++/Java/PHP code in the editor
Typed Parameters
Adding a type declaration before a parameter name (function greet(string $name)) tells PHP to enforce that type at the call site. Pass something that doesn't match — an array where a string was expected — and PHP throws a TypeError immediately, rather than silently coercing or misbehaving later.
Example: Typed Parameters
<?php
function greet(string $name) {
echo "Hello, $name!";
}
greet("Alice");
?>
Login to try C/C++/Java/PHP code in the editor
Variadic Parameters (... operator)
The ... operator before a parameter name collects any number of extra arguments into a single array inside the function, letting you write one function that accepts a flexible, unknown-in-advance number of values rather than a fixed parameter list.
Example: Variadic Parameters (... operator)
<?php
function sumAll(...$numbers) {
return array_sum($numbers);
}
echo sumAll(1, 2, 3, 4);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: