if I do serialize($obj)
, I get:
Serialization of \'Closure\' is not allowed
Is there any way these closures can be
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()
.
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));
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());
}
provide your own implementation of _sleep() and _wakeup methods