notes icon indicating copy to clipboard operation
notes copied to clipboard

PHP闭包代码输出 or PHP Closure To String

Open lanlin opened this issue 7 years ago • 0 comments

情景

有的时候为了追踪调试,可能希望了解闭包代码写了些什么。 希望能输出为字符串的形式。

方法

/**
 * convert closure to string
 *
 * @param Closure $c
 * @param $escape
 * @return string
 * @throws
 */
function closureToString(Closure $c, $escape = FALSE)
{
    $str    = "function (";
    $r      = new \ReflectionFunction($c);
    $params = [];

    foreach ($r->getParameters() as $p)
    {
        $s = '';

        if ($p->isArray())
        {
            $s .= 'array ';
        }
        else if ($p->getClass())
        {
            $s .= $p->getClass()->name . ' ';
        }

        if ($p->isPassedByReference()) { $s .= '&'; }

        $s .= '$' . $p->name;

        if ($p->isOptional())
        {
            $s .= ' = ' . var_export($p->getDefaultValue(), true);
        }

        $params[] = $s;
    }

    $str  .= implode(', ', $params);
    $str  .= ')' . PHP_EOL . '{' . PHP_EOL;
    $lines = file($r->getFileName());

    for ($l = $r->getStartLine(); $l < $r->getEndLine(); $l++)
    {
        $str .= $lines[$l] . PHP_EOL;
    }

    if ($escape)
    {
        $str = preg_replace('/[\r\n\t]/', '', $str);
    }

    $str = preg_replace('/}[,;]$/', '}', $str);

    return $str;
}

lanlin avatar Feb 01 '18 06:02 lanlin