PHP获取变量的变量名的一段代码的bug
百度一下关于php获取变量名的办法都是下面这个函数。但是用了发现有点bug
/**
* 获取变量名
*
* @param $string
* @return $string
*
* $test = "helo";
* $test2 = "helo";
* getVarName($test2);
*/
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]){
//echo "\$$k name is $k
";
//还原变量值
$src = $save;
return $k;
}
}
}
}
copy下来后发现这个怎么测试结果有时候对有时候不对,想了很久,终于弄明白,虽然很简单,但是自己还是记录下,希望遇到同样情况的同学注意。
比如:现在我测试
$test2 = "hello";
$countNum=0;
echo getVarName($test2);
//按道理应该输出为”test2“,但是输出的是"countNum",
因为函数中的
if ($src == $v) 这里存在问题 比如$src="hello", $GLOBALS里面有个变量$countNUm=0;
这时在循环的时候判断 if ($src == $v) ,即"hello"==0,比较的结果为true,类型转换的时候“hello“转为整形为0,
然后就退出循环了,得到错误的结果。
一个解决办法就是 if ($src == $v) 改为 if($src===$v),即恒等。
如果我理解错了欢迎您指正,一起进步。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.