[SOLVED] overloading classes with array accessor

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
daaaaang
Forum Newbie
Posts: 2
Joined: Tue Aug 04, 2009 8:21 pm

[SOLVED] overloading classes with array accessor

Post by daaaaang »

Hi!

I've been using Doctrine, and one of the features that I like (simply because it is pretty) is the ability to access member variables as if the object were an array. For example, all of the following lines are equivalent to each other:

Code: Select all

echo $user->username;
echo $user->get('username');
echo $user->getUsername;
echo $user['username'];
I know how to use __call to make the first three lines happen, but I've no idea how to emulate the fourth. I poured through a lot of the Doctrine code, but there is way too much of it for me to figure out this particular aspect.

Does anybody know how to do it, or even have any ideas? Let me know if I've been at all unclear.

Thank you!
Matt
Last edited by daaaaang on Wed Aug 05, 2009 1:23 pm, edited 1 time in total.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Syntactical sugar -- overloading classes with array accessor

Post by Weirdan »

daaaaang wrote:Does anybody know how to do it, or even have any ideas?
That's done by implementing ArrayAccess interface in your class. Docs are here: http://us2.php.net/arrayaccess
User avatar
daaaaang
Forum Newbie
Posts: 2
Joined: Tue Aug 04, 2009 8:21 pm

Re: Syntactical sugar -- overloading classes with array accessor

Post by daaaaang »

Thank you so much!
Matt
Post Reply