How to serialize object that has closures inside properties?

后端 未结 4 1295
面向向阳花
面向向阳花 2021-01-14 05:57

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

Serialization of \'Closure\' is not allowed

Is there any way these closures can be

相关标签:
4条回答
  • 2021-01-14 06:32

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

    0 讨论(0)
  • 2021-01-14 06:32

    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));
    
    0 讨论(0)
  • 2021-01-14 06:45

    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());
    }
    
    0 讨论(0)
  • 2021-01-14 06:52

    provide your own implementation of _sleep() and _wakeup methods

    0 讨论(0)
提交回复
热议问题