PHP "Assign by reference" 古怪

PHP "Assign by reference" oddity

我遇到了一个包含 $a = & $b; 但没有测试 $b 是否实际存在 (if (isset($b))) 的代码片段。我不确定 PHP 是如何处理这个问题的,所以我做了一个快速的裸测试,现在我更加感兴趣了。

$a = array('a'=>'b', 'x'=>'y');

$b = array();

$b[10] = &$a['a'];
$b[11] = &$a['ppp'];

var_dump($a);
var_dump($b);
echo (isset($a['ppp']) ? "SET" :" NOT SET") . "\n";
echo (isset($b[11]) ? "SET" :" NOT SET") . "\n";

它是裸代码,但输出显示的是:

感谢您首先检查修复了 'problem',但我主要是想寻求更深入的了解。发生什么事了?

解释就这么简单

If you assign, pass, or return an undefined variable by reference, it will get created.

(强调我的)

这就是你在做的;通过引用分配未定义的索引以便创建它。

Example #1 Using references with undefined variables

<?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)
?> 

Example from PHP Manual

那你还有一个问题:

Meanwhile at the same time, $b[11] shows a value NULL and isset()=FALSE even though its referent (apparently) does exist (!)

说明书上也说的很清楚

isset — Determine if a variable is set and is not NULL

isset() will return FALSE if testing a variable that has been set to NULL

因为它是 NULLisset() returns FALSE。

slot 必须存在,您才能将另一个变量作为它的别名(这就是这里发生的事情,PHP 的 "references" 并不是真正的实际事物,因为每个 "by reference" 操作都是常规操作,复制被别名取代),但它不必包含非空值,并且直到您分配它一个(通过它的名字之一)。