PHP“通过引用赋值"古怪 [英] PHP "Assign by reference" oddity

查看:24
本文介绍了PHP“通过引用赋值"古怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I came across a code snippet which included $a = & $b; but hadn't tested whether $b actually existed (if (isset($b))). I wasn't sure how PHP handled this so I knocked up a quick bare test and now I'm even more intrigued.

$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";

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

It's bare code but what the output shows is:

  • 只需 $b[11] = &$a['ppp'] 的裸赋值就足够了,var_dump($a) 被报告因为有 3 个成员而不是 2 个,即使没有为 $a['ppp'] 赋值.$a['ppp'] 被报告为有一个值 (NULL) 但也有 isset()=FALSE.

  • Just the bare assignment of $b[11] = &$a['ppp'] is enough, var_dump($a) is reported as having 3 members not 2, even though no assignment was made for $a['ppp']. $a['ppp'] is reported as having a value (NULL) but also isset()=FALSE.

同时,$b[11] 显示值 NULLisset()=FALSE 即使它的指涉对象(显然)确实存在(!)

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

我很欣赏首先检查可以解决问题",但我主要是想获得更深入的了解.发生了什么?

I appreciate that checking first fixes the 'problem', but I'm mainly looking for a deeper understanding. What's happening?

推荐答案

解释就这么简单

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

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

(强调我的)

这就是你正在做的;通过引用分配一个未定义的索引以便它被创建.

That's what you're doing; Assigning an undefined index by reference so it gets created.

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

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

PHP 手册中的示例

那么你还有一个问题:

与此同时,$b[11] 显示了一个值 NULL 和 isset()=FALSE,即使它的所指对象(显然)确实存在(!)

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

说明书上也有说明

isset — 确定是否设置了变量并且未设置NULL

isset() 如果测试已设置为 NULL 的变量将返回 FALSE

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

由于它是 NULLisset() 返回 FALSE.

Since it is NULL, isset() returns FALSE.

这篇关于PHP“通过引用赋值"古怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆