I was wondering if there was some way in PHP to duplicate some of the magic of Python attribute/key access.
I use a Mongo ORM class written by Steve Lacey called Minimongo in which he utilizes the __getattr__ and __getitem__ to reroute key and attribute flavored access and preserve the ‘document-oriented’ nature of Mongo. val = doc.foo and val = doc['foo'] become equivalent.
I was wondering if there is a similar interface in PHP that would allow the changing of how object access is handled for a class that inherits from it. I looked through the STL and couldn’t find one that filled suit. It would be greatly useful for setting up defaults. Thanks.
Have a look at __get() and __set() and ArrayAccess.
With the former you can make non-public members accessbile, as in
$obj->foo, with the latter you can access them like$obj['foo'].You can hardwire them however you like, internally.
Personally I would suggest you keep these magically-accessible properties into one single array member of the class, so you don’t end up with spaghetti code.
POC:
Consistency Milord, exactly as you asked.