what is Object Cloning in php?

后端 未结 5 1641
一个人的身影
一个人的身影 2020-11-30 23:26

Can someone explain me

  • what is Object Cloning in php?

  • When should i use clone keyword in php?

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 00:08

    Cloning is used to create a genuine copy of an object. Assigning an object to another variable does not create a copy - rather, it creates a reference to the same memory location as the object:

    a= 'b';
    $o->b= 'c';
    
    $o2= $o;
    $o2->a= 'd';
    
    var_dump($o);
    var_dump($o2);
    
    $o3= clone $o;
    $o3->a= 'e';
    var_dump($o);
    var_dump($o3);
    
    ?>
    

    This example code will output the following:

    object(stdClass)#1 (2) {
      ["a"]=>
      string(1) "d"
      ["b"]=>
      string(1) "c"
    }
    object(stdClass)#1 (2) {
      ["a"]=>
      string(1) "d"
      ["b"]=>
      string(1) "c"
    }
    object(stdClass)#1 (2) {
      ["a"]=>
      string(1) "d"
      ["b"]=>
      string(1) "c"
    }
    object(stdClass)#2 (2) {
      ["a"]=>
      string(1) "e"
      ["b"]=>
      string(1) "c"
    }
    

提交回复
热议问题