13

get_defined_vars即将(引文):

返回一个多维数组,其中包含所有已定义变量的列表,可以是环境变量、服务器变量或用户定义变量

好吧,对于我的调试任务,我只需要那些用户定义的。是否有php内置或补充功能?

编辑:好的,我没有说清楚我到底在追求什么,这是一个小例子:

<?php
/*
this script is included, and I don't have info
about how many scripts are 'above' and 'bellow' this*/


//I'm at line 133
$user_defined_vars = get_user_defined_vars();
//$user_defined_vars should now be array of names of user-defined variables
//what is the definition of get_user_defined_vars()?

?>
4

3 回答 3

17

是的你可以:

<?php
// Start
$a = count(get_defined_vars());

/* Your script goes here */
$b = 1;

// End
$c = get_defined_vars();
var_dump(array_slice($c, $a + 1));

将返回:

array(1) {
  ["b"]=>
  int(1)
}
于 2012-11-29T15:24:57.330 回答
9

对数组进行一点操作怎么样?

$testVar = 'foo';
// list of keys to ignore (including the name of this variable)
$ignore = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', '_SERVER', '_ENV', 'ignore');
// diff the ignore list as keys after merging any missing ones with the defined list
$vars = array_diff_key(get_defined_vars() + array_flip($ignore), array_flip($ignore));
// should be left with the user defined var(s) (in this case $testVar)
var_dump($vars);

// Result: 
array(1) {
    ["testVar"]=>string(3) "foo"
}
于 2012-11-29T16:10:44.540 回答
0

似乎是您问题的一个很酷的解决方案:

<?php
// Var: String
$var_string = 'A string';

// Var: Integer
$var_int = 55;

// Var: Boolean
$var_boolean = (int)false;



/**
 * GetUserDefinedVariables()
 * Return all the user defined variables
 * @param array $variables (Defined variables)
 * @return array $user_variables
 */
function GetUserDefinedVariables($variables){;
    if (!is_array($variables))
        return false;

    $user_variables = array();

    foreach ($variables as $key => $value)
        if (!@preg_match('@(^_|^GLOBALS)@', $key))
            $user_variables[$key] = $value;

        return $user_variables;
}


echo '<pre>'.print_r(
                        GetUserDefinedVariables(
                                        get_defined_vars()
                                                ), true).'</pre>';
?>
于 2012-11-29T15:26:31.607 回答