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.

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

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?