PHP Call by Value
In PHP, the parameters of a function are passed by value by default. Call by value is a mechanism in which values of actual parameters are copied to the formal parameters of the called function and any change made to the formal parameter within the called function has no effect on the value of the actual parameter.
Syntax
The syntax for a function in PHP using call by value is as follows:
function functionName($param1, $param2){
//code block
}
Example
Let's take an example to understand how call by value works in PHP:
function increment($num1){
$num1++;
echo "Inside function: ".$num1."<br>";
}
$num1 = 5;
increment($num1);
echo "Outside function: ".$num1;
Output
The output of the above code will be:
Inside function: 6
Outside function: 5
Explanation
In the above example, we are passing the value of $num1
to the increment()
function. While executing the increment()
function, we are increasing the value of $num1
by 1. However, this change is only reflected within the function and doesn't affect the value of $num1
outside the function.
Use
Call by value is useful when you want to preserve the original value of a variable passed to a function and create a modified copy of it within the function.
Important Points
- Parameters in PHP are passed by value by default.
- Copying of value takes place when actual parameters are passed to the formal parameters.
- Changes made to formal parameters within the function do not affect the actual parameters that were passed to the function.
- If you do want to modify the value of the actual parameter, you can use call by reference.
Summary
In PHP, call by value is a mechanism in which values of actual parameters are copied to the formal parameters of the called function and any change made to the formal parameter within the called function has no effect on the value of the actual parameter. Parameters in PHP are passed by value by default. To modify the value of actual parameters, you can use call by reference.