问题
Is there a way to view the variables set in each stack frame in a backtrace? I can come pretty close with a combination of debug_backtrace(true)
to get the objects, get_object_vars
on each object to get $this vars, the args
key in each backtrace frame, and get_defined_vars
to get globals, but any temporary variables set within a function I can't find a way to retrieve.
Here's an example situation:
function method1($foo) {
$temp = method2($foo + 1);
foreach ($temp as $t) {
method2($t);
}
}
function method2($bar) {
$temp2 = $bar->value + $_GET['val'];
debug();
}
function debug() {
// to be created
$global_scope = get_defined_vars();
$bt = debug_backtrace(true);
}
I can get $foo
and $bar
via the args
key in the backtrace, the object variables of $bar
through get_object_vars
, and the globals through get_defined_vars
. I want to get the value of $temp2
and $temp
as well.
回答1:
Install and Enable XDebug on your (local) server. Then use xdebug_get_declared_vars(). Make sure that you set xdebug.collect_vars
to On in your xdebug .ini
file.
Example:
<?php
class strings {
static function fix_strings($a, $b) {
foreach ($b as $item) {
}
var_dump(xdebug_get_declared_vars());
}
}
strings::fix_strings(array(1,2,3), array(4,5,6));
?>
Returns:
array
0 => string 'a' (length=1)
1 => string 'b' (length=1)
2 => string 'item' (length=4)
Example from xdebug.org
Note, that the function only returns variables in the scope where the function xdebug_get_declared_vars()
is called in.
回答2:
Alter your debug to take 1 param. Then just pass in get_defined_vars. This will give you an array of all the vars in the local scope.
来源:https://stackoverflow.com/questions/3418413/get-variables-in-scope-at-each-php-backtrace-level