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!

  • 相关阅读:
    HDU 4970 Killing Monsters(树状数组)
    HDU 1541 Stars(树状数组)
    HDU 1541 Stars(树状数组)
    POJ 1990 MooFest(树状数组)
    POJ 1990 MooFest(树状数组)
    关于论坛数据库的设计(分表分库等-转)
    struts2零配置參考演示样例
    [ATL/WTL]_[中级]_[保存CBitmap到文件-保存屏幕内容到文件]
    转【翻译】怎样在Ubuntu 12.04上配置Apache SSL证书
    《简单的飞机大战》事实上不简单(1)
  • 原文地址:https://www.cnblogs.com/gameboy90/p/2232682.html
Copyright © 2011-2022 走看看