代码之家  ›  专栏  ›  技术社区  ›  B T

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

  •  0
  • B T  · 技术社区  · 15 年前

    我想知道有没有什么办法可以做到以下几点:

    function whatever($parameter)
    {  
        echo funky_reflection_function();
    }
    
    whatever(5 == 7); // outputs "5 == 5" (not true or 1)
    

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

    4 回复  |  直到 15 年前
        1
  •  0
  •   Josh Davis    15 年前

    反省在那里帮不了你,但你也许可以用 debug_backtrace()

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

    很明显,这是非常老套的,不应该真的依赖,但如果你试图调试的东西,那么它可能会帮助你实现这一点。这个函数会给你整条线,现在你必须解析它来找到用来调用你的表达式的表达式。 whatever() 功能。

        2
  •  0
  •   timdev    15 年前

    泽德应该从他的评论中做出回答。如果他这样做了,就给他投票。

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

    对函数参数(5==7)进行求值,求值的结果使它进入whatever()的作用域。

    我必须说我很好奇你为什么要这样做。通常当我看到一些奇怪的东西时,我会想“这可能是设计不好的结果”——在这种情况下,感觉更像是某种诱惑性的疯狂……一定要告诉我。

        3
  •  0
  •   J.C. Inacio    15 年前

    如前所述,在传递给函数之前会计算所有参数,因此不会传递“原始代码”。

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

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

      somefunc(“回声5==7;”)

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

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

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

        4
  •  0
  •   B T    15 年前

    让你知道,这是我现在使用的函数:

    // 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)
            }
        }
    }
    
    推荐文章