【问题标题】:Serializing anonymous functions in php在php中序列化匿名函数
【发布时间】:2013-05-08 04:57:37
【问题描述】:

有没有办法在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?为什么?
  • 假设我有一些 ui 组件库,并且我想在输出中为用户提供一定程度的自定义(通过匿名函数)。并且我希望能够在会话中为对象的保存状态充电。
  • 如果接受的问题答案只是指向另一个问题答案的链接,则该问题是重复的。

标签: php serialization anonymous-function


【解决方案1】:

Get string representation of anonymous function

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';
}

【讨论】:

    【解决方案2】:

    看看我对 PHP Super Closure 的回复:

    Exception: Serialization of 'Closure' is not allowed

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-11
      • 2015-01-27
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 2017-01-17
      • 2011-03-13
      • 2020-03-11
      相关资源
      最近更新 更多