Search code examples
phpserializationanonymous-function

Serializing anonymous functions in php


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?


Solution

  • Get string representation of anonymous function

    https://3v4l.org/CEmqV

    UPDATE 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";
    

    Return String

    function(){ 
        return 'test';
    }