博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
大话设计模式第九章---原型模式PHP实现
阅读量:7035 次
发布时间:2019-06-28

本文共 2310 字,大约阅读时间需要 7 分钟。

首先,PHP对象clone参考资料:

 

Object Cloning

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's  method if possible). An object's  method cannot be called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

 

void __clone ( void )

Once the cloning is complete, if a  method is defined, then the newly created object's  method will be called, to allow any necessary properties that need to be changed.

 

 

Example #1 Cloning an object

instance = ++self::$instances; } public function __clone() { $this->instance = ++self::$instances; }}class MyCloneable{ public $object1; public $object2; function __clone() { // Force a copy of this->object, otherwise // it will point to same object. $this->object1 = clone $this->object1; }}$obj = new MyCloneable();$obj->object1 = new SubObject();$obj->object2 = new SubObject();$obj2 = clone $obj;print("Original Object:\n");print_r($obj);print("Cloned Object:\n");print_r($obj2);?>

The above example will output:

Original Object:MyCloneable Object(    [object1] => SubObject Object        (            [instance] => 1        )    [object2] => SubObject Object        (            [instance] => 2        ))Cloned Object:MyCloneable Object(    [object1] => SubObject Object        (            [instance] => 3        )    [object2] => SubObject Object        (            [instance] => 2        ))

 

PHP中,其实用clone关键字加上__clone()便可以实现浅复制与深复制,__clone()方法就是那个抽象出来的接口。

 

 

转载于:https://www.cnblogs.com/wy0314/p/4770924.html

你可能感兴趣的文章
创建一个多线程的QTcpServer
查看>>
视频取首帧,并保存到SDCard
查看>>
Servlet-获得web.xml配置参数信息
查看>>
Spring初始化容器—实例化bean对象
查看>>
android 自定义系统键盘
查看>>
MySQL 查询优化器(总结)
查看>>
2014年6月28日
查看>>
android读取手机验证码
查看>>
awk 日常实例
查看>>
Python直接赋值、浅拷贝和深度拷贝解析
查看>>
何时进行重构?
查看>>
centos6.2x64系统配置本地yum源
查看>>
Java Strategy 模式简介
查看>>
CDH-cdh5.8.3离线安装--Mysql5.7二进制部署
查看>>
flask request 对象
查看>>
【VMware虚拟化解决方案】Horizon-View GPU虚拟化
查看>>
Redis 对象
查看>>
Android应用程序获取ROOT权限的方法
查看>>
KVM主机在线增加硬盘爬坑记
查看>>
【Linxu学习004】Bash Shell 相关
查看>>