duan35557593 2013-08-27 17:17
浏览 34
已采纳

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?
  • 写回答

1条回答 默认 最新

  • douke1905 2013-08-27 17:31
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)