PHP to get the variable name for a piece of code bug analysis. The copy code is as follows: *** get variable name ** @ param $ string * @ return $ string ** $ testhelo; * $ test2helo; * getVarName ($ test2 ); * functiongetVarName (storage Institute
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 http://www.bkjia.com/PHPjc/323861.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/323861.htmlTechArticle code is as follows:/*** get variable name ** @ param $ string * @ return $ string *** $ test = "helo"; * $ test2 = "helo "; * getVarName ($ test2); */function getVarName (// storage Institute...