在PHP中有没有一种方法可以获取用户声明的变量?

14

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

?>

你的意思是用户定义的与类定义中声明的吗? - Ray
什么是用户定义变量?是你在自己的脚本中直接定义的变量吗?PHP如何区分它和在某个外部文件中被require / include定义的变量? - Marc B
不,这不是关于类变量的问题,我需要在全局范围内定义变量。 - Miloš Đakonović
用户定义意味着我正在调试的应用程序在某个地方声明了这些变量。 - Miloš Đakonović
$GLOBALS 数组怎么样? - Bogdan Burym
3个回答

18

是的,你可以:

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

会发生什么事情,会话变量和发送的变量(例如 $_POST)呢?不过我喜欢你的想法,因此给你点赞。 - Eyal Alsheich
1
@EyalAlsheich 在此示例中,定义在 $a 之前的所有内容都将被隐藏。$_POST 是在执行任何用户代码之前定义的。对于会话,这取决于您是否使用 session_start(); 或会话自动启动。 - eisberg
这真的很棒。这里是最佳答案。 - ankr

8

让我们来进行一些数组操作怎么样?

$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"
}

这个答案最符合我的需求。谢谢。 - Miloš Đakonović
@Crisp 你缺少一些预定义变量 - eisberg
这个回答极其误导,因为它缺少在局部作用域中定义的所有变量,这意味着在正确组织的代码中有99%的变量没有被考虑到。 - Your Common Sense

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

1
这将隐藏所有以下划线和以GLOBALS开头的用户定义变量。 - eisberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接