Bug analysis of a piece of code for getting variable names in PHP
Source: Internet
Author: User
Baidu's methods for obtaining variable names in php are the following functions. However, we found a bug.
The code is as follows:
/**
* Get the variable name
*
* @ Param $ string
* @ Return $ string
*
* $ Test = "helo ";
* $ Test2 = "helo ";
* GetVarName ($ test2 );
*/
Function getVarName (& $ src ){
// Store the current variable value
$ Save = $ src;
// Store all variable values
$ Allvar = $ GLOBALS;
// Do not directly traverse $ GLOBALS in the function, and stack problems may occur.
Foreach ($ allvar as $ k => $ v ){
// The variable values are the same and 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 changes, it is the same variable.
If ($ src = $ GLOBALS [$ k]) {
// Echo "\ $ k name is $ k
";
// Restore the variable value
$ Src = $ save;
Return $ k;
}
}
}
}
After copying it, I found out how to test the result. sometimes it's wrong. after thinking for a long time, I finally figured it out. although it's very simple, I still keep a record, and I hope you will pay attention to it in the same situation.
For example, now I test
The code is as follows:
$ Test2 = "hello ";
$ CountNum = 0;
Echo getVarName ($ test2 );
// The output is test2, but the output is countNum ",
Because
If ($ src = $ v) there is a problem here, for example, $ src = "hello", $ GLOBALS contains a variable $ countNUm = 0;
In this case, when looping, judge if ($ src = $ v), that is, "hello" = 0, and the comparison result is true, during type conversion, "hello" is converted into an integer of 0,
Then exit the loop and get the wrong result.
One solution is to change if ($ src = $ v) to if ($ src = $ v), that is, constant.
If I understand it wrong, please correct it and make progress together.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.