8

有没有办法在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;
}

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

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

4

2 回答 2

4

Take a look to my response here about PHP Super Closure :

Exception: Serialization of 'Closure' is not allowed

I hope it helps.

于 2013-11-01T15:52:45.223 回答
1

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

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';
}
于 2021-11-11T19:56:13.480 回答