php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71870 [][index] syntax emits a "Undefined variable: offset" notice
Submitted: 2016-03-21 15:15 UTC Modified: 2016-03-21 15:48 UTC
From: nish dot aravamudan at canonical dot com Assigned: nikic (profile)
Status: Closed Package: Arrays related
PHP Version: 7.0.4 OS: Ubuntu 16.04
Private report: No CVE-ID: None
 [2016-03-21 15:15 UTC] nish dot aravamudan at canonical dot com
Description:
------------
https://3v4l.org/T9HLm

Note that with PHP5, no "undefined variable offset" is emitted. I believe this is a BC break in PHP7.0. Also, I found this page: https://wiki.php.net/rfc/uniform_variable_syntax, which explicitly mentions: "E.g. empty([]['a']) will no longer throw an undefined offset notice."

This is seen with php-zeta-console-tools tests, and leads to a test failure.

Test script:
---------------
<?php
error_reporting(-1);

class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;
$obj[][0] = 'Append';

Expected result:
----------------
No notice to be emitted.

Actual result:
--------------
Notice: Undefined variable: offset in /in/T9HLm on line 32

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-03-21 15:48 UTC] nikic@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: nikic
 [2016-03-21 15:48 UTC] nikic@php.net
Good timing! I've fixed this bug yesterday: https://github.com/php/php-src/commit/1f6d27d3d2cf8a5113946a55a297441bb4c70ddf

It still does throw the "indirect modification" notice, because offsetGet doesn't return by reference.
 [2016-03-21 16:03 UTC] nish dot aravamudan at canonical dot com
Great, thank you!
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 15:01:29 2024 UTC