Home > Backend Development > PHP Tutorial > php object-oriented Clone and serialization

php object-oriented Clone and serialization

WBOY
Release: 2016-08-08 09:22:48
Original
1006 people have browsed it

There are three options for copying objects:

1, direct copy $a = $b

This is a shallow copy, when $a is changed, $b will also change, because They point to the same heap area

2, clone copy $a = clone $b

This copy seems to be a deep copy. When $a changes, $b will not follow. At the same time, PHP provides the magic method __Clone() to customize Clone replication. Which attributes do not want to be copied and what changes are needed during the replication process can be customized in the __clone() method.

However, this copying method has a flaw. It should be noted that if the type of a certain attribute in the class is another class, then this attribute will not be deep copied during Clone. , isn’t it embarrassing? Of course, this shortcoming can be made up for by the magic method __clone. Just create a new new class for this attribute in the __clone() method.

	class test{
		private $name;
		private $sex;
		private $demo;
		public function __construct($name,$sex,$demo){
			$this->name = $name;
			$this->sex  = $sex;
			$this->demo = $demo;
		}
		public function __set($key,$value){
			$this->{$key} = $value;
		}
		public function __get($key){
			return $this->{$key};
		}
		public function __clone(){
			$this->name='null';  //这里可以自定义clone
		}
	}
Copy after login
	class demo{
		private $name;
		public function __construct($name='demo01'){
			$this->name = $name;
		}
		
		public function __set($key,$value){
			$this->{$key} = $value;
		}
		
		public function __get($key){
			return $this->{$key};
		}
	}
Copy after login
	$t = new test('aa', 'bb',new demo('d01'));
	$d = clone $t;
	//$d->name='nihao';
	$d->demo->name = 'd02';
	var_dump($t);   //结果 $t->demo->name   d02
Copy after login
Use clone to make up

		public function __clone(){
			$this->name='null';
			$this->demo = new demo('init');
		}
Copy after login
3, serialized copy

$b = unserialize(serialize($t));
Copy after login
This way you can implement attributes without using the clone magic method A deep copy of the reference type was made.

The above introduces PHP object-oriented Clone and serialization, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template