is there any way to serialize an anonymous function in php?
i have found this http://www.htmlist.com/development/extending-php-5-3-closures-with-serialization-and-reflection/
protected function _fetchCode()
{
// Open file and seek to the first line of the closure
$file = new SplFileObject($this->reflection->getFileName());
$file->seek($this->reflection->getStartLine()-1);
// Retrieve all of the lines that contain code for the closure
$code = '';
while ($file->key() < $this->reflection->getEndLine())
{
$code .= $file->current();
$file->next();
}
// Only keep the code defining that closure
$begin = strpos($code, 'function');
$end = strrpos($code, '}');
$code = substr($code, $begin, $end - $begin + 1);
return $code;
}
but it depends on the internal implementation of closure.
are there any future plans to implement closure serialization?
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
Definition and Usage The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.
unserialize() From the above code, we have a variable with serialized data, $string . We can unserialize the value of the variable using unserialize() function to get back to the original value of the complex array, $myvar. print_r( $newvar );
Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function.
Take a look to my response here about PHP Super Closure :
Exception: Serialization of 'Closure' is not allowed
I hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With