【问题标题】:PHP - "Undefined Index" notice not raised when referencing (&) an un-instantied element of an associative arrayPHP - 引用(&)关联数组的未实例化元素时未引发“未定义索引”通知
【发布时间】:2018-12-08 11:07:33
【问题描述】:

我正在查看来自 answer 的这段代码:

$string = 'item1:item2:itemx';

$res = array();

$temp = &$nested_array;
foreach(explode(':', $string) as $key) {
    $temp = &$temp[$key];
}

感谢$temp = &$temp[$key],结果:

$res = [
  "item1" => [
    "item2" => [
      "itemx" => & null
    ]]]

我不明白为什么&temp[$key] 实例化关联[$key => null]$temp[$key] 没有。

我做了一些调试,对于第一个 $key (item1):

  1. $a = $temp[$key]:
    • 给出“未定义索引”通知
    • 转储$a 返回null。
    • 转储$temp 返回null。
  2. $a = &$temp[$key]:
    • 不给“未定义索引”通知
    • 转储$a 返回null。
    • 转储$temp[$key] 返回null。
    • 转储$temp 返回: ["item1" => & null]

这意味着 $temp = & $temp[$key] 也实例化 $temp[$key] 或等效地在它前面加上:

$temp = &temp[$key]; <=> $temp[$key] = null; $temp = &temp[$key];

我想了解这是否在 php 文档中的某处进行了解释(我搜索了但我没有找到任何东西)或者我是否遗漏了一些东西。

谢谢

【问题讨论】:

    标签: php arrays indexing reference undefined


    【解决方案1】:

    这在文档中有解释。创建引用时会创建未定义的变量:

    注意
    如果您通过引用分配、传递或返回未定义的变量,它将被创建。

    示例 #1 使用未定义变量的引用

    <?php
    function foo(&$var) { }
    
    foo($a); // $a is "created" and assigned to null
    
    $b = array();
    foo($b['b']);
    var_dump(array_key_exists('b', $b)); // bool(true)
    
    $c = new StdClass;
    foo($c->d);
    var_dump(property_exists($c, 'd')); // bool(true)
    ?>
    

    https://secure.php.net/manual/en/language.references.whatdo.php

    【讨论】:

    • 这就是我要找的东西!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2011-12-04
    • 1970-01-01
    • 2011-02-10
    • 2017-05-25
    • 2012-12-08
    • 2015-12-15
    相关资源
    最近更新 更多