有没有办法在PHP中获取用户声明的变量?

时间:2012-11-29 15:21:07

标签: php

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()?

?>

3 个答案:

答案 0 :(得分:14)

是的,你可以:

<?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)
}

答案 1 :(得分: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"
}

答案 2 :(得分:0)

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

<?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>';
?>