如何序列化在属性中有闭包的对象? [英] How to serialize object that has closures inside properties?
问题描述
如果我做 serialize($ obj)
,我得到:
不允许序列化Closure
Serialization of 'Closure' is not allowed
有没有什么方法可以在序列化时忽略这些闭包?我不需要它们,当我反序列化字符串反正(这些属性的值可以为null或任何)。
Is there any way these closures can be ignored when serializing? I don't need them when I unserialize the string anyway (value of those properties can be null or whatever).
我的类看起来像这样:
Class Node{
protected $attrs = array();
}
$ attrs
是一个关联数组,可以包含一些元素是闭包,如
$ attrs ['validator'] = function(){...}
$attrs
is an associative array that can contain some elements that are closures, like
$attrs['validator'] = function(){...}
推荐答案
我写了一个函数,允许任何异常
序列化。
I've written a function that allows any Exception
to be serialized. This is done by flattening complex values in the backtrace.
https://gist.github.com/Thinkscape/805ba8b91cdce6bcaf7c
<?php
try {
// exception gets thrown here, i.e.
// throw new Exception();
} catch (Exception $exception) {
flattenExceptionBacktrace($exception);
$serialized = serialize($exception);
$unserialized = unserialize($serialized);
print_r($unserialized->getTraceAsString());
}
这篇关于如何序列化在属性中有闭包的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!