PHP参考概念与数组

时间:2019-07-20 12:02:56

标签: php arrays

&``符号如何在PHP中用于数组?

当我执行以下代码时

<?php
    $cfg=array();
    $curpath=array();
    $name="check";
    array_push($curpath, strtolower($name));
    $ptr =& $cfg;
    /*what happens here*/
    $ptr =& $ptr[$name];

    print("\ncfg\n");
    print_r($cfg);
 ?>

执行上述代码后,输出以下内容:

cfg
Array ( [check] => )  

请解释以下声明

 $ptr = &$cfg;
/*what happens here*/
 $ptr =& $ptr[$name];

2 个答案:

答案 0 :(得分:0)

在这里,&表示该数组是通过引用分配的。这意味着不是将值从$cfg复制到$ptr,而是两个实际上都指向完全相同的数组。如果使用$ptr修改阵列,则使用$cfg访问阵列时将看到这些更改。同样,如果使用$cfg修改数组,则使用$ptr访问数组时将看到更改。

&中没有$ptr = &$cfg;的情况下,$cfg的值将被复制到$ptr。在这种情况下,您将拥有两个完全不同的阵列。这样,对$ptr的更改将不会反映在$cfg中,反之亦然。

例如,如果我们有:

$cfg = ["item 1" => 1, "item 2" => 2];
$ptr = &$cfg;

$ptr["item 1"] = 999;

echo $cfg["item 1"];
echo $ptr["item 1"];

输出将是:

999 999

但是,如果将$ptr = &$cfg更改为$ptr = $cfg,则输出将是: 1个 999

在第二种情况下,原始的$ cfg保持不变。

答案 1 :(得分:0)

您的示例对我而言真的没有意义,但让我们看看:

$config = array();
$currentPath = array();

// you pushed "check" into the end of the $currentPath array
$name = "check";
array_push($currentPath, strtolower($name));

echo "currentPath:\r\n";
var_dump($currentPath);
// array (
//     0 => 'check',
// )

echo "config:\r\n";
var_dump($config);
// array(0) {
// }


// $ptr (pointer) is actually a reference.
// you now have a $reference to $config.
// (btw it should be written $foo = &$bar and NOT $foo =& $bar)
$reference = &$config;


// "what happens here"
// $reference is empty. so $reference["check"] does not exist.
// you create an offset "check" at $reference, so at $config.
// (i have no idea how - if somebody know why please let me know)
$reference = &$reference[$name];

// what happen here is
// - offset $config["check"] created
// - the reference of $config["check"] has been assigned to $reference (overwritten previous $reference var)

echo "config:\r\n";
var_dump($config);
// array(1) {
//     ["check"]=>
//   &NULL
// }


// $reference points now to $config["check"], so ...
$reference = 123;
// should set $config["check"] to 123

echo "config:\r\n";
var_dump($config);
// array(1) {
//     ["check"]=>
//   &int(123)
// }

一个更“现实”的例子可能是:

// empty config
$config = array();
// ...
// create config offset "check" with default value NULL
$name = 'check';
$config[$name] = null;
// ...

var_dump($config);
// array(1) {
//     ["check"]=>
//   NULL
// }

// using a reference to $config["check"] (for w/e reasons)
$check = &$config[$name];
// ...
// update $config["check"]
$check = 123;

var_dump($config);
// array(1) {
//     ["check"]=>
//   &int(123)
// }

unset($check); // release reference

var_dump($config);
// array(1) {
//     ["check"]=>
//   int(123)
// }

@all PHP为什么要创建偏移量$config["check"] 执行$reference = &$reference[$name];时? PHP是否应该显示未定义的索引通知?