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!

  • 相关阅读:
    网页嵌入视频常用方式
    2.4 对字母数字的混合排序
    VC操作Image的三种方法(收集)
    VC 窗口出现白屏闪烁的解决办法
    Invalidate(TRUE)与Invalidate(FALSE)区别(前者会发送WM_ERASEBKGND消息全部刷新,然后使用WM_PAINT消息绘制,而后者只发送WM_PAINT消息)
    QT 文件拖放事件dropEvent和dragEnterEvent
    百用随身系统 Veket Linux
    C#通过属性名称获取(读取)属性值的方法
    搭建一个完整的Java开发环境
    XSD实例
  • 原文地址:https://www.cnblogs.com/gameboy90/p/2232682.html
Copyright © 2011-2022 走看看