Home > Article > Backend Development > Deeply understand the difference between passing by value and passing by reference in PHP
The difference between PHP value passing and reference passing. When to pass by value and when to pass by reference
(1) Pass by value: Any changes to the value within the function scope will be ignored outside the function
(2) Pass by reference: Function scope Any changes to the internal value will also reflect these modifications outside the function
(3) Advantages and Disadvantages:
A: When passing by value, PHP must copy the value. Especially for large strings and objects, this can be a costly operation.
B. Passing by reference does not require copying the value, which is very good for improving performance.
<?php header('content-type:text/html;charset=utf-8'); //探讨一下 array , null, 对象 ,资源的默认传递方式 // 结论 (1) array 默认是值传递,通过加 & 可以引用传递 // (2) null 默认是值传递,通过加 & 可以引用传递 // (3) 资源 是值传递.通过加 & 可以引用传递 // (4) 对象默认也是值传递,但是对象值传递是对象标识符 $hero = array('no1'=>'蝙蝠侠', 'no2'=>'超人'); $hero2 = &$hero; $hero2['no1'] = '蜘蛛侠'; echo '<pre class="brush:php;toolbar:false">'; var_dump($hero); var_dump($hero2); $a = null; $b = &$a; $b = 'abc'; var_dump($a, $b);
Recommended video tutorial: PHP video tutorial
The above is the detailed content of Deeply understand the difference between passing by value and passing by reference in PHP. For more information, please follow other related articles on the PHP Chinese website!