php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72899 Iterating over an ArrayObject does not call offsetGet
Submitted: 2016-08-19 16:46 UTC Modified: 2016-08-19 17:08 UTC
From: c dot tigra at gmail dot com Assigned:
Status: Not a bug Package: SPL related
PHP Version: 7.1.0beta3 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: c dot tigra at gmail dot com
New email:
PHP Version: OS:

 

 [2016-08-19 16:46 UTC] c dot tigra at gmail dot com
Description:
------------
offsetGet() don't called if ArrayObject uses in foreach(). It directly returns value from private storge of ArrayObject.

Test script:
---------------
class Some extends ArrayObject {
    function __construct(){
        parent::__construct(array("key"=>"storged value"),ArrayObject::ARRAY_AS_PROPS);
    }

    function offsetGet($index){
        return "offsetGet called";
    }
}

$obj=new Some();
print $obj->key."<br>";
foreach($obj as $key=>$val){
    print $val."<br>";
}


Expected result:
----------------
offsetGet called
storged value

Actual result:
--------------
offsetGet called
offsetGet called


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-08-19 17:08 UTC] requinix@php.net
-Summary: tested in https://3v4l.org/ +Summary: Iterating over an ArrayObject does not call offsetGet -Status: Open +Status: Not a bug
 [2016-08-19 17:08 UTC] requinix@php.net
The Expected and Actual are backwards.
https://3v4l.org/G6VW0

It doesn't call offsetGet for two reasons:
1. Because offsetSet (nor the rest of the ArrayAccess interface) is not used for iteration.
2. Because ArrayObject implements IteratorAggregate, which *is* used for iteration. It does so by using ArrayIterator (by default).

Sounds like you want to change what values are exposed during iteration? I can't imagine that ever being a good idea, but whatever. Try
(a) overriding getIterator with your own iterable values https://3v4l.org/2LCBG or
(b) using your own class for iteration https://3v4l.org/7tMHH
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 20:01:28 2024 UTC