tags:

views:

4419

answers:

1

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.

+18  A: 

If you extend ArrayObject, or implement ArrayAccess then you can do what you want.

http://uk2.php.net/arrayobject

http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html

Mat Mannion
Very cool.It doesn't seem like either of those can be used with array functions like array_key_exists, etc.Is that correct?
Mark Biek
Correct, use offsetExist() method instead.
Michał Rudnicki
Would I do that on the instantiated object itself?if( $foo->offsetExists('fooKey') ){}
Mark Biek
You can use isset, I believe, but you can't use array_key_exists.
Mat Mannion
Cast an ArrayObject as an Array to use it with array functions, e.g. array_values((array) $some_array_object). It's an annoying extra step, but it works.
pd