


Variable name Bug analysis of a piece of code to obtain the variable name of a variable in PHP
Jul 29, 2016 am 08:46 AMCopy the code The code is as follows:
/**
* 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 variables Value
$allvar = $GLOBALS;
//Do not traverse $GLOBALS directly in the function, stack problems will occur
foreach($allvar as $k=>$v){
//The variable values are the same, but they may not be the same Variable, 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 As it changes, it's the same variable.
if ($src == $GLOBALS[$k]){
//echo "$$k name is $k
";
//Restore variable value
$src = $save;
return $k;
}
}
}
}
After copying it, I found that the test results are sometimes correct and sometimes wrong. After thinking about it for a long time, I finally figured it out. Although it is very simple, I still recorded it. I hope that students who encounter the same situation will pay attention. .
For example: Now I test
Copy the code The code is as follows:
$test2 = "hello";
$countNum=0;
echo getVarName($test2);
//Logically the output should be " test2", but the output is "countNum",
because there is a problem with
if ($src == $v) in the function, such as $src="hello", there is a variable $countNUm=0 in $GLOBALS;
At this time, if ($src == $v) is judged during the loop, that is, "hello" == 0, the comparison result is true. During type conversion, "hello" is converted into an integer and is 0,
Then exit the loop , and got wrong results.
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.
The above introduces the bug analysis of a piece of code for obtaining the variable name of a variable in PHP, including the variable name. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
