获取PHP变量名的字面值

内容如标题。

例如有一个变量

$var1="varname";

function(mixed $var)必须返回string."var"

1、简单变量可以利用php的$GLOBALS数组返回.

cn.php.net 写道
$GLOBALS
$GLOBALS — References all variables available in global scope


An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

Report a bug Examples

Example #1 $GLOBALS example

<?php
function test() {
$foo = "local variable";

echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>
The above example will output something similar to:

$foo in global scope: Example content
$foo in current scope: local variable

 as $GLOBALS是一个数组引用。具有$key=>value,利用foreach,找到相应的项,变可以找到$key了。

 

 

 

function getVarName(&$src) {
    //存储当前变量值
    $save = $src;
    //存储所有变量值
    $allvar = $GLOBALS;
    //在函数中不要直拉遍历$GLOBALS,会出现堆栈问题
    foreach($allvar  as $k=>$v) {
        //变量值相同,可能不是相同变量,因多个变量的值可能相同
        if ($src == $v) {
            //改变当前变量$src的值
            $src = 'change';
            //如果$GLOBALS[$k]也跟着改变,那就是同一个变量。
            if ($src == $GLOBALS[$k])  {
               return $k;
            }
        } 
    }
    //还原变量值
    $src = $save;
}
$test  = "helo";
$test2 = "helo";
getVarName($test);

 

你可能感兴趣的:(.net,PHP)