使用反射将原始代码作为参数传递给PHP函数

时间:2009-09-19 05:59:00

标签: php reflection

我想知道是否有办法执行以下操作:

function whatever($parameter)
{  
    echo funky_reflection_function();
}

whatever(5 == 7); // outputs "5 == 5" (not true or 1)

我不乐观,但有人知道我能做些什么疯狂的黑客攻击吗?

4 个答案:

答案 0 :(得分:0)

Zed应该从他的评论中得出答案。如果他这样做,就给他起动。

答案是:不,你不能这样做。

评估函数参数(5 == 7),并且评估的结果使其成为whatever()的范围。

我必须说我很好奇你为什么要这样做。通常当我看到一些奇怪的东西时,我开始想“这可能是糟糕设计的结果” - 在这种情况下,感觉更像是某种诱人的疯狂......告诉你。

答案 1 :(得分:0)

反思对你没有帮助,但你可以用debug_backtrace()

烹饪
function funky_reflection_function()
{
    $trace = debug_backtrace();
    $file = file($trace[1]['file']);
    return $file[$trace[1]['line'] - 1];
}

显然,这是非常hacky,不应该真正依赖,但如果你正在尝试调试的东西,那么它可能会帮助你实现这一目标。该函数将为您提供整行,现在您必须解析它以找到用于调用whatever()函数的表达式。

答案 2 :(得分:0)

正如已经回复的那样,在传递给函数之前会对任何参数进行求值,因此没有传递“原始代码”。

既然你要求'疯狂黑客',还有几种方法可以将随机“代码”作为参数传递:

  • 作为字符串 - 可以在create_function()或eval()中使用:

    somefunc(“echo 5 == 7;”)

  • 作为一个匿名函数 - 从php 5.3开始,我们有闭包和匿名函数:

    somefunc(function(){return 5 == 7;});

正如蒂姆所说,一些更多的“背景”信息确实会有所帮助,因为我承认疯狂的黑客攻击并不是好设计的结果:)

答案 3 :(得分:0)

只是为了让你知道,这是我现在正在使用的功能:

// gets the line number, class, parent function, file name, and the actual lines of the call
// this isn't perfect (it'll break in certain cases if the string $functionName appears somewhere in the arguments of the function call)
public static function getFunctionCallLines($fileName, $functionName, $lineNumber)
{   $file = file($fileName);

    $lines = array();
    for($n=0; true; $n++)
    {   $lines[] = $file[$lineNumber - 1 - $n];
        if(substr_count($file[$lineNumber - 1 - $n], $functionName) != 0)
        {   return array_reverse($lines);
        }
        if($lineNumber - $n < 0)
        {   return array(); // something went wrong if this is being returned (the functionName wasn't found above - means you didn't get the function name right)
        }
    }
}