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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
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

Pull Requests

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-2025 The PHP Group
All rights reserved.
Last updated: Tue Jul 15 05:01:33 2025 UTC