NYCPHP Meetup

NYPHP.org

[nycphp-talk] object getter/setter methods

Derek DeVries devrieda at gmail.com
Thu Mar 10 22:39:49 EST 2005


For every object that I create I end up making countless getter/setter
methods. My User class is littered with methods like getUsername(),
getEmail(), etc. This can add up to thousands of lines of code for my
objects. Is there a better way around this? A method like this would
cut down on code:

/**
 * Get the value of the given property.
 *  eg. $username = $user->get('username');
 * @param   string  $var    Name of the property
 * @return  mixed
 */
function get($var)
{
    return isset($this->{$var}) ? $this->{$var} : null;
}

However this would allow for access to any of the properties, which I
don't necessarily want. Has anyone tried using the above approach to
success/failure? I suppose another approach would be to make all of
the accessable properties in an associative array. I am aware of
php5's __get/__set magic methods but am currently still using v4. I
like the idea of having the specific getX()/setX() methods in my API
because it seems clearer for others to read. However I feel that I'm
writing a lot of unnecessary code.

I've run into this article titled: Why getter and setter methods are
evil. http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

This is a java article that advocates eliminating accessors. I'm not
sure if I want to go to that extreme, but I guess there are a few good
points.



More information about the talk mailing list