Home > Backend Development > PHP Tutorial > PHP gets the variable name of a variable code bug_PHP tutorial

PHP gets the variable name of a variable code bug_PHP tutorial

WBOY
Release: 2016-07-21 14:57:55
Original
692 people have browsed it

Baidu’s method of obtaining variable names in PHP is the following function. But I found some bugs after using it

/**
* Get variable name
*
* @param $string
* @return $string
*
* $test = "helo";
* $test2 = " helo";
* getVarName($test2);
*/
function getVarName(&$src){
//Storage the current variable value
$save = $src;
//Storage all variable values
$allvar = $GLOBALS;
//Do not traverse $GLOBALS directly in the function, stack problems will occur
foreach($allvar as $k=>$v){
//Variables The values ​​are the same, but they may not be the same variables, because the values ​​of multiple variables may be the same
if ($src == $v){
//Change the value of the current variable $src
$src = 'change' ;
//If $GLOBALS[$k] also changes, it is the same variable.
if ($src == $GLOBALS[$k]){
//echo "$$k name is $k
";
//Restore variable value
$src = $save;
return $k;
}
}
}
}
After copying it, I found out how the test results are sometimes correct and sometimes not. After thinking about it for a long time, I finally got it I understand that although it is very simple, I still record it myself and hope that students who encounter the same situation will pay attention.

For example: Now I test

$test2 = "hello";
$countNum=0;
echo getVarName($test2);
//It stands to reason that it should The output is "test2", but the output is "countNum",
because there is a problem with the
if ($src == $v) in the function, such as $src="hello", there is a variable in $GLOBALS $countNUm=0;

At this time, if ($src == $v) is judged during the loop, that is, "hello"==0, the comparison result is true, and "hello" is converted during type conversion The integer value is 0,

then exits the loop and gets the wrong result.

One solution is to change if ($src == $v) to if ($src===$v), which is identical.

If I understand it wrong, you are welcome to correct me and let us make progress together.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363934.htmlTechArticleBaidu’s method of obtaining variable names in PHP is the following function. But I found some bugs after using it /** * Get variable name * * @param $string * @return $string * * $test = helo; * $...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template