Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement an array-like object in PHP?

I want to implement an object that behaves like an array. It should be used in this way:

$var = new CustomCollection(retrieveFromWebService());
echo $var[0]; // legal
$var[0] = 'a'; // illegal

Can this be done in PHP, using magic methods or another mechanism?

like image 993
pyon Avatar asked Dec 07 '25 03:12

pyon


2 Answers

Your CustomCollection class will need to implement the built-in ArrayAccess interface.

See also: http://code.google.com/p/phpraise/source/browse/trunk/phpraise/core/collection/RaiseCollection.php

like image 65
mauris Avatar answered Dec 08 '25 17:12

mauris


I think ArrayAccess is what you are looking for.

like image 42
Explosion Pills Avatar answered Dec 08 '25 18:12

Explosion Pills