Note that there are some explanatory texts on larger screens.

plurals
  1. POdetect closure in __sleep to prevent their serialization
    text
    copied!<p>When I'm trying to serialize an object which has members including closures an exception is thrown. To avoid the serialization of the members including closures I tried the following:</p> <pre><code>function __sleep(){ $ref = new ReflectionClass($this); $props = $ref-&gt;getProperties(); foreach ($props as $prop){ $name = $prop-&gt;name; if (is_callable($this-&gt;$name)===false){ $dream[] = $prop-&gt;name; } } return $dream; } </code></pre> <p>Unfortunately this does not work. Is there a better way to detect whether a property is a closure or not.</p> <p><strong>EDIT: I solved my problem by letting the closure know whether to serialize or not</strong></p> <p>To do this I am wrapping the closure itself. Here's an example:</p> <pre><code>/** * Wrapper-class to prevent closure to be serialized. */ class WrappedClosure { private $closure = NULL; protected $reflection = NULL; public function __construct($function){ if ( ! $function instanceOf Closure) throw new InvalidArgumentException(); $this-&gt;closure = $function; $this-&gt;reflection = new ReflectionFunction($function); } /** * When the instance is invoked, redirect invocation to closure. */ public function __invoke(){ $args = func_get_args(); return $this-&gt;reflection-&gt;invokeArgs($args); } // do nothing on serialization public function __sleep(){} // do nothing on serialization public function __wakeup(){} } // Assigning a wrapped closure to a member $myObject-&gt;memberHoldingAClosure = // Wrapping the closure new WrappedClosure( function (){ echo "I'am the inner closure."; } ) ); // the serialization doesn't throw an exception anymore serialize($myObject); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload