Variable name a bug analysis of a section of code that gets the variable name of a variable in PHP

Source: Internet
Author: User
Copy CodeThe code is as follows:


/**
* Get variable name
*
* @param $string
* @return $string
*
* $test = "Helo";
* $test 2 = "Helo";
* Getvarname ($test 2);
*/
Function Getvarname (& $SRC) {
Store current variable values
$save = $SRC;
Store all variable values
$allvar = $GLOBALS;
Do not traverse $globals directly in the function, there will be a stack problem
foreach ($allvar as $k = = $v) {
Variable values are the same, 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, that is the same variable.
if ($src = = $GLOBALS [$k]) {
echo "\$ $k name is $k
";
Restore variable values
$SRC = $save;
return $k;
}
}
}
}


Copy down found this how test results sometimes wrong, think for a long time, finally understand, although very simple, but I still record, hope to meet the same situation of students attention.
For example: Now I'm testing

Copy the Code code as follows:


$test 2 = "Hello";
$countNum = 0;
Echo Getvarname ($test 2);
The reason should be output as "test2", but the output is "Countnum",


Because the functions in the
if ($src = = $v) There are problems such as $src= "Hello", $GLOBALS there is a variable $countnum=0;
At this time in the loop to determine if ($src = = $v), that is, "Hello" ==0, the result of the comparison is true, when the type conversion "Hello" to the shaping of 0,
It then exits the loop and gets the wrong result.
One solution is to change if ($src = = $v) to if ($src = = = $v), which is identity.
If I understand wrong, you are welcome to correct and improve together.

The above describes the variable name in PHP to get variable name of a section of code bug analysis, including the variable name of the content, I hope to be interested in PHP tutorial friends helpful.

  • Contact Us

    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.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.