search
Homephp教程php手册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),即恒等。
如果我理解错了欢迎您指正,一起进步。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

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.