Bug #76308 [Nab]: reference to unset variable
| From: | bichinhoverde at spwinternet dot com dot br | Date: | Mon, 07 May 2018 08:21:09 +0000 |
| Subject: | Bug #76308 [Nab]: reference to unset variable | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-215142@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=76308&edit=1
ID: 76308
User updated by: bichinhoverde at spwinternet dot com dot br
Reported by: bichinhoverde at spwinternet dot com dot br
Summary: reference to unset variable
Status: Not a bug
Type: Bug
Package: Variables related
Operating System: Linux
PHP Version: 7.2.5
Block user comment: N
Private report: N
New Comment:
This is a strange behavior.
If I do $c = $a['b']; I get a notice for trying to get the value of an undefined variable.
But $c =& $a['b']; silently creates the variable.
I don't mind the array being created implicitly, but a notice should be generated since I am
referencing something that does not exist.
Trying to get the value of something undefined: notice.
Trying to get the reference of something undefined: perfectly fine.
Previous Comments:
------------------------------------------------------------------------
[2018-05-07 08:05:13] requinix@php.net
A reference to a variable or array/key can only happen if the source exists. If it does not then
what would the reference be to? However if $a[b] does not exist then what would happen to $c? What
would it be a reference to?
So PHP must create $a[b] automatically. Doing so also requires creating the $a array, since that
doesn't exist yet either, but just like during $a[b]=123 PHP does not warn when it happens
automatically.
So
1a. There is no warning for implicitly creating arrays. This is not related to references.
1b. There is no warning when $a[b] was implicitly created because you did, after all, want a
reference to it.
2. Since $a[b] had to be created, count($a) will return 1.
This is also mentioned in the docs.
http://php.net/manual/en/language.references.whatdo.php
> Note: If you assign, pass, or return an undefined variable by reference, it will get created.
------------------------------------------------------------------------
[2018-05-07 07:49:29] bichinhoverde at spwinternet dot com dot br
Description:
------------
Creating a reference to an unset variable does not generate a warning/notice. Also, variable changes
after the reference is created.
Test script:
---------------
<?php
error_reporting(E_ALL);
$c =& $a['b'];
echo count($a);
Expected result:
----------------
1. A warning/notice should be generated for referencing an unset variable.
2. Variable should not change. count($a) should return zero and cause warning/notice.
Actual result:
--------------
1. No warning/notice.
2. count($a) return 1.
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=76308&edit=1