What is the meaning of pass by value and pass by reference?
In this tutorial, we are going to discuss pass by value vs pass by reference. In C programming, you have learned the local scope and global scope. Pass by value and pass by reference depend on this local and global scope. In Local Scope, if you have defined the variable inside the function, then you can not use variable out of the function. In Global Scope, if you have defined any variables inside the function, then you can use that variable outside the function. The argument in the pass by value affects the locally, whereas, in the pass by reference, arguments effect globally.
Pass by Value in PHP
Pass by value is just a technique in which we pass the arguments. We learn to pass by value through a foreach loop.In which we create an array and pass variable as argument inside a function.
In the pass by value, the argument is affected only locally (Inside the function)
Example
<?php
function pass_by_value() {
}
$result = array(1,2,3,4);
pass_by_value($result);
foreach ($result as $row) {
print "
$row";
}
?>
Run
In above example , we pass the argument inside pass_by_value() function. We can print the array values inside the function only. It is not able to display outside the function because of the argument in the pass by value effects only locally.
Pass by reference
In the Pass by reference the argument values affected globally (i.e outside the function).
If you want to use a variable as a reference you have to placed (&) symbol before the variable to be referenced. Through the pass by reference we are handling in our only copy of the variable, and the function directly modifies that variable like as below example .
Pass by value vs reference example
In the below example, we pass the argument for pass by value. After that, we use & sign with the variable pass as references.
In the pass by value, the arguments effect inside the function only rather than in pass by reference, the effect of the argument outside the function.
Let's create an example for pass by value vas pass by reference.
Example
<?php
function func_value($val)
{
$val=1000;
echo 'value val: '.$val.'
';
}
$n1=30;
func_value($n1);
echo '
n1='.$n1.'
';
function func_ref(&$val) ///pass by refernce
{
$val=1000;
echo ' Reference val:'.$val.'
';
}
$n1=30;
func_ref($n1);
echo '
n1='.$n1.'
';
?>
Run
In the above example, we pass the arguments first to pass by value. If we display the value of the variable inside the function, then it takes the value and does not take the value out of the function. In a similar way, passing a variable reference in the function as an argument through the pass by reference. Here, we can display the variable value outside the function that is defined inside the function.
Hence!
Pass by value depends on the local scope and pass by reference depends on the global scope.
Recommended Posts:-