Home > Backend Development > PHP Problem > Deeply understand the difference between passing by value and passing by reference in PHP

Deeply understand the difference between passing by value and passing by reference in PHP

王林
Release: 2023-02-23 15:56:01
Original
3157 people have browsed it

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(&#39;content-type:text/html;charset=utf-8&#39;);

    //探讨一下 array , null, 对象 ,资源的默认传递方式
    // 结论 (1) array 默认是值传递,通过加 & 可以引用传递
    //      (2)  null 默认是值传递,通过加 & 可以引用传递
    //      (3) 资源  是值传递.通过加 & 可以引用传递
    //        (4) 对象默认也是值传递,但是对象值传递是对象标识符    
    $hero = array(&#39;no1&#39;=>&#39;蝙蝠侠&#39;, &#39;no2&#39;=>&#39;超人&#39;);

    $hero2 = &$hero;
    $hero2[&#39;no1&#39;] = &#39;蜘蛛侠&#39;;
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    var_dump($hero);
    var_dump($hero2);


    $a = null;
    $b = &$a;
    $b = &#39;abc&#39;;

    var_dump($a, $b);
Copy after login

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!

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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template