在PHP中序列化匿名函数

9

有没有办法在php中序列化匿名函数?

我找到了这个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;
}

但这取决于闭包的内部实现。

是否有未来计划实现闭包序列化?


你想在某个时候将 PHP 函数传递给 PHP 吗?为什么? - BlitZ
假设我有一些UI组件库,并且我想通过匿名函数为用户提供一定程度的输出自定义。同时,我希望能够在会话中重新加载并保存对象的状态。 - Jarry
4
可能是 Exception: Serialization of 'Closure' is not allowed 的重复问题。 - Siguza
如果问题的被接受答案只是指向另一个问题的答案链接,那么这个问题就是重复的。 - faintsignal
2个回答

4

3

获取匿名函数的字符串表示形式

https://3v4l.org/CEmqV

更新 PHP8

<?php

function closure_to_str($func)
{
    $refl = new \ReflectionFunction($func); // get reflection object
    $path = $refl->getFileName();  // absolute path of php file
    $begn = $refl->getStartLine(); // have to `-1` for array index
    $endn = $refl->getEndLine();
    $dlim = PHP_EOL;
    $list = explode($dlim, file_get_contents($path));         // lines of php-file source
    $list = array_slice($list, ($begn-1), ($endn-($begn-1))); // lines of closure definition
    $last = (count($list)-1); // last line number

    if((substr_count($list[0],'function')>1)|| (substr_count($list[0],'{')>1) || (substr_count($list[$last],'}')>1))
    { throw new \Exception("Too complex context definition in: `$path`. Check lines: $begn & $endn."); }

    $list[0] = ('function'.explode('function',$list[0])[1]);
    $list[$last] = (explode('}',$list[$last])[0].'}');


    return implode($dlim,$list);
}

$dog2 = function(){ 
    return 'test';
};

echo closure_to_str($dog2)."\n\n";

返回字符串
function(){ 
    return 'test';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接