How to serialize object that has closures inside properties?

人走茶凉 提交于 2019-12-01 06:53:32

问题


if I do serialize($obj), I get:

Serialization of 'Closure' is not allowed

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).

My class looks smth like this:

Class Node{

  protected $attrs = array();

}

$attrs is an associative array that can contain some elements that are closures, like $attrs['validator'] = function(){...}


回答1:


I've written a function that allows any Exception to be serialized. This is done by flattening complex values in the backtrace.

Source:

https://gist.github.com/Thinkscape/805ba8b91cdce6bcaf7c

Usage:

<?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());
}



回答2:


It's simple: You can't. A closure is not serializable. If you want to create "something similar", you can use objects of a class implementing __invoke() instead of the closures.

If you don't need the closures (or you can recreate them yourself while unserializing) you can implement Serializable and don't take the closures into account while serializing. This interface (implementing serialize() and unserialize()) should be prefered over __sleep()/__wakeup().




回答3:


provide your own implementation of _sleep() and _wakeup methods




回答4:


To serialize properties of an object while ignoring closures :

$properties = array_map(function ($property) {
    try {
        return serialize($property);
    } catch (\Exception $e) {
        return null;
    }
}, get_object_vars($this));


来源:https://stackoverflow.com/questions/14235760/how-to-serialize-object-that-has-closures-inside-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!