Skip to content
Advertisement

How find the source code for an eval’d function in PHP?

I am trying to find a way to get the source code for (user defined) PHP functions in a string.

For normal code this is easy, using reflection I can find the file and line numbers where the function is defined; then I can open the file and read the function source code.

This will not work if a function is defined in eval’d code. I do not want to keep record of all eval’d code.

Is this possible? If yes, then how?

Example code:

function myfunction() {
    echo "Test";
}
eval('
  function myevalfunction() {
    echo "Test";
  }
');

$a = new ReflectionFunction('myfunction');
echo $a;

$b = new ReflectionFunction('myevalfunction');
echo $b;

Output:

Function [ <user> <visibility error> function myfunction ] {
  @@ test.php 3 - 5
}
Function [ <user> <visibility error> function myevalfunction ] {
  @@ test.php(11) : eval()'d code 2 - 4
}

Advertisement

Answer

How about you define your own eval-function, and do the tracking there?

function myeval($code) {
     my_eval_tracking($code, ...);  # use traceback to get more info if necessary
     # (...)
     return eval($code);
}

That said, I do share a lot of Kent Fredric’s feelings on eval in this case.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement