PHP “Assign by reference” oddity

谁都会走 提交于 2019-12-01 14:50:00

Explanation is as simple as this

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

(emphasis mine)

That's what you're doing; Assigning an undefined index by reference so it gets 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

Then you have another question:

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

That is also explained clearly on the manual

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

Since it is NULL, isset() returns FALSE.

The slot has to exist for you to be able to alias another variable to it (which is really what's going on here, PHP's "references" aren't really actual things as much as each "by reference" operation is a regular operation with copying replaced by aliasing), but it doesn't have to contain a non-null value, and doesn't until you assign it one (through either of its names).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!