PHP Super Accessor

I’m currently working on a little project using the twitter api, and part of it involves an object for tweets. Each instance of the tweet object has properties for ID, screen name of the author, the tweet text, time stamp, author’s profile picture, and the tweet it was posted in reply to.

Now being the good little PHP 5 developer that I am, each of these properties is declared as private, and if you want to retrieve the data from a different scope, you need to use an accessor function. Of course this means I have to essentially write the following function six times, once for each property:

public function getVar() { return $this->var; }

While I was labouriously copying and pasting this function over and over (six is a big number, and I’m lazy) an idea hit me, why not use the same accessor function for all the properties, a ‘Super Accessor’:

public function get($var) { return $this->$var; }

That one function can now return any of the objects properties, and if later I were to add new properties, that super accessor would still work! I think I’m on to something here.

Obviously it’s a bit basic there, and sometimes a private property should stay just that; private. So I added an array of property names that are allowed to be accessed, and then the super accessor just has to check to see if the property be requested is in the allow list before returning it. I also added an isset() check, as I really hate the old ‘Undefined variable’ warning. Here’s the final code:

private $can_access = array('id', 'text', 'date');

public get($var)
    if(in_array($var, $this->can_access))
        return isset($this->$var) ? $this->var : false;

    return false;

Using this code if you can just pass in the name of the property you want to access, and the function will return the value. But if the property you request is not in the allowed array, or it simply doesn’t exist in the object, the function returns false. Of course, if you’re working as part of a team, an exception should really be thrown in those situations, otherwise other developers could waste a lot of time trying to figure out why certain properties are always false.

It seems too simple, but I’ve never seen this technique anywhere else. I’d love some feed back on it, whether you’ve seen it before, you think it sucks, or you’ll be using it from now on.


Posted in: Programming by Matt Bearman on 1st October 2010 at 11:57 pm
Tags: , , ,

No Responses to “PHP Super Accessor” - (Leave a comment)

No comments yet.

RSS | TrackBack URL

Leave a comment