0

看看以下内容:

文件1.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
);*/

文件2.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. 怎么可能有一个重复的数组索引?(参见文件 1 的示例)。
  2. 为什么在第二个示例中,变量$1未定义但确实出现在get_defined_vars()数组中?我如何访问它?
  3. 在示例 1 中,为什么$1不被 覆盖parse_str
4

1 回答 1

1

您所拥有的与执行以下操作没有什么不同:

<?php

$GLOBALS[1] = 'foo';

或者

<?php

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

因为 PHP 的变量名称空间在内部保存为关联数组,所以您可以轻松地在该全局名称空间中创建数组键,它们作为数组条目完全有效,但变量名称是非法的。

您不能通过这些非法变量名访问这些值,因为它们实际上是语法错误。但是作为数组条目,它们就像任何其他数组条目一样,所以

 <?php

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

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

注意变量 variable $$foo。虽然您可以分配给潜在的非法变量名,但不能使用 var-vars 来访问该非法变量名。

于 2013-08-27T17:31:09.443 回答