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.
Nope, casting just results in a normal PHP array -- losing whatever functionality your ArrayObject-derived class had. Check this out:
As expected, the array_keys() call fails. In addition, is_array($blah) returns false. But if you change the constructor line to:
then you just get a normal PHP array (is_array($blah) returns true, and array_keys($blah) works), but all of the functionality of the ArrayObject-derived subclass is lost (in this case, case-insensitive keys no longer work). Try running the above code both ways, and you'll see what I mean.
PHP should either provide a native array in which the keys are case-insensitive, or make ArrayObject be castable to array without losing whatever functionality the subclass implements, or just make all array functions accept ArrayObject instances.
If you extend
ArrayObject
or implementArrayAccess
then you can do what you want.