Making a PHP object behave like an array?

Posted by Mark Biek on Stack Overflow See other posts from Stack Overflow or by Mark Biek
Published on 2008-09-15T17:50:04Z Indexed on 2010/04/25 9:53 UTC
Read the original article Hit count: 183

Filed under:
|
|

I'd like to be able to write a PHP class that behaves like an array and uses normal array syntax for getting & setting.

For example (where Foo is a PHP class of my making):

$foo = new Foo();

$foo['fooKey'] = 'foo value';

echo $foo['fooKey'];

I know that PHP has the _get and _set magic methods but those don't let you use array notation to access items. Python handles it by overloading __getitem__ and __setitem__.

Is there a way to do this in PHP? If it makes a difference, I'm running PHP 5.2.

© Stack Overflow or respective owner

Related posts about php

Related posts about oop