Analysis of Object Reference and Replication Instances in php

  • 2021-12-13 16:33:51
  • OfStack

This article example describes object reference and replication in php. Share it for your reference, as follows:

Quote


$tv2 = $tv1;

Or


$tv2 = &$tv1;

In the above two ways, the effect is one. It can be understood as a hard link in linux.

Cloning (shallow replication)


$tv2 = clone $tv1;

"Shallow copy": All variables of the copied object have the same values as the original object, while all references to other objects still point to the original object. That is, shallow replication only replicates the object under consideration, not the object it references.

Deep replication


$tv4 = unserialize(serialize($tv1));

Compared with "shallow copy", there is also a "deep copy": all variables of the copied object have the same values as the original object, except those that refer to other objects. That is to say, deep copy copies all the objects referenced by the object to be copied once.

Code Sample


<?php
header("Content-type:text/html;charset=utf-8");
class TvControl{
}
class Tv{
  private $color;
  private $tvControl;
  function __construct(){
    $this->color = "black";
    $this->tvControl = new TvControl();
  }
  function setColor($color){
    $this->color = $color;
  }
  function getColor(){
    return $this->color;
  }
  function getTvControl(){
    return $this->tvControl;
  }
}
$tv1 = new Tv();
$tvControl1 = $tv1->getTvControl();
echo " Original class: ";
var_dump($tv1);
echo "<hr/>";
$tv2 = $tv1;
echo " Reference class: ";
var_dump($tv2);
echo "<hr/>";
$tv3 = clone $tv1;
echo " Cloning (shallow replication): ";
var_dump($tv3);
echo "<hr/>";
$tv4 = unserialize(serialize($tv1));
echo " Deep replication: ";
var_dump($tv4);

Output:

Original class:
object(Tv)[1]
private 'color' = > string 'black' (length=5)
private 'tvControl' = >
object(TvControl)[2]
Reference class:
object(Tv)[1]
private 'color' = > string 'black' (length=5)
private 'tvControl' = >
object(TvControl)[2]
Cloning (shallow replication):
object(Tv)[3]
private 'color' = > string 'black' (length=5)
private 'tvControl' = >
object(TvControl)[2]
Deep replication:
object(Tv)[4]
private 'color' = > string 'black' (length=5)
private 'tvControl' = >
object(TvControl)[5]

Reference article: https://www.ofstack.com/article/167631. htm

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: