zoukankan      html  css  js  c++  java
  • PHP中对象的clone和引用的区别(Object Cloning and Passing by Reference in PHP)

    InPHPeverything’s a reference! I’ve heard it so many times in my practice. No, these words are too strong! Let’s see some examples.

    Some developers think that everything's passed by reference in PHP.

     

    Passing Parameters by Reference

    Clearly when we pass parameters to a function it’s not by reference. How to check this? Well, like this.

    
    
    1 function f($param)
    2 {
    3 $param++;
    4 }
    5
    6 $a=5;
    7 f($a);
    8
    9 echo$a;

    Now the value of $a equals 5. If it were passed by reference, it would be 6. With a little change of the code we can get it.

    
    
    1 function f(&$param)
    2 {
    3 $param++;
    4 }
    5
    6 $a=5;
    7 f($a);
    8
    9 echo $a;

    Now the variable’s value is 6.

    So far, so good. Now what about copying objects?

    Objects: A Copy or a Cloning?

    We can check whether by assigning an object to a variable a reference or a copy of the object is passed.

    
    
     1 class C
    2 {
    3 public $myvar=10;
    4 }
    5
    6 $a=new C();
    7 $b=$a; //这里是引用 和 $b=&$a的效果是一样的哦,只不过是显式和隐式引用罢了
    8
    9 $b->myvar=20;
    10
    11 // 20, not 10
    12 echo$a->myvar;

    The last line outputs 20! This makes it clear. By assigning an object to a variable PHP pass its reference. To make a copy there’s another approach. We need to change $b = $a, to $b = clone $a;

    
    
     1 class C
    2 {
    3 public $myvar=10;
    4 }
    5
    6 $a=new C();
    7 $b= clone $a; //这里是copy
    8
    9 $b->myvar=20;
    10
    11 // 10, not 20
    12 echo$a->myvar;

    Arrays by Reference

    What about arrays? What if I assign an array to a variable?

    
    
    1 $a=array(20);
    2
    3 $b=$a; //和对象相反,这里是copy
    4 $b[0]=30;
    5
    6 var_dump($a);

    What do you think is the value of $a[0]? Well, the answer is: 20! So $b is a copy of the array “a”. Instead you should assign explicitly its reference to make “b” point to “a”.

    1 $a=array(20);
    2
    3 $b=&$a; //这里是引用$b[0]=30;
    4
    5 var_dump($a);

     

    Now $a[0] equals 30!

    I think this could be useful!

  • 相关阅读:
    Spring Boot 的单元测试和集成测试
    Containers vs Serverless:你选择谁,何时选择?
    Java13新特性
    Java中创建对象的5种方法
    最好的重试是指数后退和抖动
    杂谈:面向微服务的体系结构评审中需要问的三个问题
    使用Quarkus在Openshift上构建微服务的快速指南
    Java EE—最轻量级的企业框架?
    AQS机制
    JVM-内存模型
  • 原文地址:https://www.cnblogs.com/gameboy90/p/2232682.html
Copyright © 2011-2022 走看看