获取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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值