get_defined_vars()和parse_str如何工作?

Take a look at the following:

file1.php

$a = 1;
$$a = "one"; // $1 = one

var_dump( ${'1'} ); // string(3) "one"

$str = "1=_one&foo=bar";
parse_str($str);

var_dump( ${'1'}, $foo ); 
// string(3) "one" 
// and not "_one", so apparently $1 is not overwritten by parse_str


print_r( get_defined_vars() );
/*
Array(
    [a] => 1
    [1] => one                  <----- index is 1
    [str] => 1=_one&foo=bar
    [1] => _one                 <----- index is 1, again ?!?
    [foo] => bar
);*/

file2.php

$str = "1=_one&foo=bar";
parse_str($str);

var_dump( ${'1'}, $foo ); // will give "undefined variable: 1" and string(3) "bar"

print_r( get_defined_vars() );
/* if you run this from the command line you may have more variables in here:
Array(
    [a] => 1
    [str] => 1=_one&foo=bar
    [1] => _one                 <--- variable 1 is defined here
    [foo] => bar
);*/
  1. How is it possible to have a duplicate array index? (see example of file1).
  2. How come in the 2nd example, variable $1 is undefined but does show up in the get_defined_vars() array? How do I access it?
  3. In example 1, how come $1 is not overwritten by parse_str?

What you've got isn't any different than doing something like:

<?php

$GLOBALS[1] = 'foo';

or

<?php

$foo = 1;
$$foo = 'one';

Because PHP's variable name space is kept internally as an associative array, you can easily create array keys in that global namespace that are perfectly valid as array entries, but are illegal variable names.

You can't access the values via those illegal variable names, because they are in fact syntax errors. But as array entries, they're just like any other array entry, so

 <?php

 $GLOBALS['1'] = 'one';
 $foo = 1;

 echo $1; // syntax error
 echo $$foo; // outputs warning: undefined variable 1
 echo $GLOBALS[1]; // outputs 'one'

Note the variable variable $$foo. While you can ASSIGN to potentially illegal variable name, you can't use var-vars to ACCESS that illegal variable name.