For PHP testing scripts I need a function report() that will report results of some expressions, like:
report(in_array(null, $array));
report(in_array(false, $array));
# etc...
The output should look like:
in_array(null, $array) => false
in_array(false, $array) => true
So I want to print the expression along with the result. Thus in the report function I need some means how to print the expression which was given by the caller:
function report($expr)
{
SOME_FUNCTION($expr)
# function I'm looking for!!
# function which would write the string 'in_array(null, $array)' to output!
echo " => ";
echo $expr;
echo "<br>";
}
Is there any such function that would dump the expression as given by the caller?
I know this can’t be “normal” function, this would need to be somehow bound to PHP internals. But if there are magic things like debug_print_backtrace(), __FUNCTION__ or __LINE__, then I think there still can be some chance…
Directly, no there is no clean method to do what you want.
With that said, you could use debug_backtrace to get the stack. Then, all you need to do is walk the stack back one (go to the 2nd array element), and you have the file and line information. Then, you’d need to parse that line to extract the function name and the inputs.
It wouldn’t be clean. It wouldn’t likely be easy. And it wouldn’t be 100% reliable. But it should work for most cases…
here’s a simple case of a utility function to do that. Just call it with the function name, and it’ll give you the literal caller of the function:
And here’s an example:
Would output: