java php序列化_PHP: 序列化 - Manual

这篇博客介绍了一种实现继承对象序列化的方法,无需指定要序列化的属性。通过抽象类`DefaultModel`实现`Serializable`接口,序列化时移除`PDO`对象,反序列化时重新创建`PDO`对象。示例中展示了如何使用`RealModel`继承`DefaultModel`,并设置和获取`myVar`属性,然后进行序列化和反序列化操作。
摘要由CSDN通过智能技术生成

My solution that let you serialize inherited objects.

Without specify what need to be serialized.

We want to get rid of PDO object in this example.

abstract class DefaultModel() implements \Serializable

{

/**

* @var PDO

*/

private $pdo;

/**

* Serialize object

*

* @return string

*/

public function serialize()

{

$serializable = get_object_vars($this);

// unset property name that hold PDO instance

unset($serializable['pdo']);

return serialize($serializable);

}

/**

* Unserialize object

*

* @param string $serialized Serialized object

* @return DefaultModel

*/

public function unserialize($serialized)

{

$unserialized = unserialize($serialized);

// recreate PDO object

$this->pdo = $this->createDBObject();

if(is_array($unserialized) === true) {

foreach($unserialized as $property => $value) {

$this->{$property} = $value;

}

}

}

}

class RealModel extends DefaultModel

{

private $myVar;

public function setMyVar($value)

{

$this->myVar = $value;

}

}

$model = new RealModel();

$model->setMyVar('123456');

$serialized = serialize($model);

$serialized = $model->serialize();   // will also work

print_r($serialized);

$unserialized = unserialize($serialized);

print_r($unserialized);

Hope this help.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值