Home > Backend Development > PHP Problem > The difference between passing by reference and passing by value in php

The difference between passing by reference and passing by value in php

王林
Release: 2023-02-24 07:12:02
Original
3500 people have browsed it

The difference between passing by reference and passing by value in php

Pass by value

Any changes to the value within the scope of the function will be ignored outside the function. Passing by value copies the value. , two variables point to two memory addresses.

$a = 6;
$b = $a; // 这是值传递,把 $a 的值拷贝给了 $b,在内存中 $a 和 $b 不在一个地址中,更改任意变量的值对对方无影响
$b = 7;
echo $a; // 输出:6

function foo($b){
	echo ++$b;
}
foo($b); // 输出:8   
echo $b; // 输出:7    说明函数内的改变对函数外的值没有影响,因为,当 $b 传入函数内的时候是值传递,
会把值在内存中拷贝一份存入一个新的内存地址中
Copy after login

Pass by reference

Any changes to the value within the function scope will also reflect these modifications outside the function. Pass by reference is to transfer a variable The memory address identifier is passed to a variable inside and outside, and the two variables eventually point to the same memory address.

$a = 6;
$b = &$a;
$b = 7;
echo $a; // 输出:7 

function foo(&$c){
	echo ++$c;
}
foo($b); // 输出:8   
echo $b; // 输出:8    说明函数内的改变对函数外的值有影响,因为,当 $b 传入函数内的时候是引用传递,
函数体内的$b和外部的$b实际上是指向同一个内存地址,所以一个改变,另外一个变量的值也会改变
Copy after login
function func(&$arr){
	$arr['a'] = [];
	$arr = &$arr['a'];
	$arr['b'] = '333';
	var_dump($arr);
}

$arr = [
    'a' => '111',
    'b' => '222'
];

func($arr);
var_dump($arr);
/**
# 第一个输出:
array(1) {
  ["b"]=> string(3) "333"
}

# 第二个输出:
array(2) {
  ["a"]=> array(1) {
      ["b"]=> string(3) "333"
  }
  ["b"]=> string(3) "222"
}
*/
Copy after login

The above example is obviously passed in by reference. Why do two $arr print out different results?
Because there is a step operation $arr = &$arr['a']; after this step, the pointing address of $arr in the function has changed, pointing to $arr['a'], so the results of the two printings no the same.

Note: The default pass-by-value for objects in PHP is generally used when passing parameters need to be changed within the function body and when external variables need to be affected. Values ​​are generally used at other times. transfer.

Recommended tutorial: PHP video tutorial

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template