Home >Backend Development >PHP Problem >What is the difference between pass by value and pass by reference in php?

What is the difference between pass by value and pass by reference in php?

青灯夜游
青灯夜游Original
2019-10-17 13:11:243203browse

What is the difference between pass by value and pass by reference in php?

Value transfer: within the function scope, changing the variable value will not affect the variable value outside the function.

Passing by reference: Within the function scope, any changes to the value are also reflected outside the function, because the memory address is passed by reference.

Type two pieces of code and you can see the difference between the two. Let’s look at the essence through the phenomenon

function sum($a){
  $a++;
  $b = $a;
  return $b;
}
$a = 10;
echo sum($a).&#39;<br />&#39;;//11
echo $a;//10
function sum(&$a){
  $a++;
  $b = $a;
  return $b;
}
$a = 10;
echo sum($a).&#39;<br />&#39;;//11
echo $a;//11

The difference between the two pieces of code lies in the parameters of the function sum. One is to pass the value $ a, and the other is passing reference &$a. The result is that the value of $a does not change after passing the value. On the contrary, the value of $a changes after passing the reference. Children who have learned C language here will understand what is going on. What is pushed on the stack is a copy of the reference.

Since the reference points to a certain variable, the operation on the reference is actually the operation on the variable it points to. (The function is the same as passing a pointer, except that there is no need to dereference) & is a symbol pointing to the address of a variable. The formal parameter &$a in the function sum is actually the actual parameter $a, so it is passed into sum for an operation. After that, the value of the actual parameter $a actually changes, that's all.

Explanation:

The value of the original parameter in pass by value remains the original value after calling other functions, while pass by reference changes the original value. When passing values ​​according to the method of passing by value, if the original value needs to be changed, the code needs to be copied. If the value is large enough or it is a large string of strings, the code will be more and more repetitive, while passing by reference will There is no need to copy PHP code, which has a great advantage in improving performance.

For more PHP related knowledge, please visit php中文网!

The above is the detailed content of What is the difference between pass by value and pass by reference in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn