php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #49454 Call ArrayObject::getArrayCopy() when casting an ArrayObject to an array
Submitted: 2009-09-03 11:55 UTC Modified: 2010-12-29 13:19 UTC
Votes:3
Avg. Score:3.3 ± 0.5
Reproduced:0 of 1 (0.0%)
From: info at adaniels dot nl Assigned:
Status: Open Package: SPL related
PHP Version: * OS: *
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: info at adaniels dot nl
New email:
PHP Version: OS:

 

 [2009-09-03 11:55 UTC] info at adaniels dot nl
Description:
------------
It would be nice if you could affect the behaviour of casting an ArrayObject to an array by overloading the getArrayCopy() method.

This would be usefull to create lazy load arrays.

Reproduce code:
---------------
<?php

class Items extends ArrayObject
{
	/**
	 * Stub for loading an item.
	 * @return object
	 */
	public function load($id)
	{
		return (object)(array('id'=>$id));
	}

	public function offsetGet($key)
	{
		$item = parent::offsetGet($key);
		if (!is_object($item)) {
			$item = $this->load($item);
			$this->offsetSet($key, $item);
		}
		return $item;
	}
	
	public function getArrayCopy()
	{
		$array = parent::getArrayCopy();
		foreach ($array as $i=>&$item) {
			if (!is_object($item)) {
				$item = $this->load($item);
				$this->offsetSet($i, $item);
			}
		}
		return $array;
	}
}

$a = new Items();
$a[] = 'jan';
$a[] = 'piet';

var_dump($a[0]);
var_dump((array)$a);

Expected result:
----------------
object(stdClass)#2 (1) {
  ["id"]=>
  string(3) "jan"
}
array(2) {
  [0]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    string(3) "jan"
  }
  [1]=>
  object(stdClass)#3 (1) {
    ["id"]=>
    string(4) "piet"
  }
}


Actual result:
--------------
object(stdClass)#2 (1) {
  ["id"]=>
  string(3) "jan"
}
array(2) {
  [0]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    string(3) "jan"
  }
  [1]=>
  string(4) "piet"
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-12-29 13:19 UTC] jani@php.net
-Package: Feature/Change Request +Package: SPL related -Operating System: Linux / Ubuntu 9.04 +Operating System: * -PHP Version: 5.3.0 +PHP Version: *
 
PHP Copyright © 2001-2017 The PHP Group
All rights reserved.
Last updated: Sun Nov 19 01:31:42 2017 UTC