Attribute Accessors - Ruby VS. PHP

Typically in objects you don't set/get the attributes directly, you use a method. This allows you to do type checking when setting the data or to format it a certain way when getting the data. In php I would use something like this:

    function setAttack( $atk ) { $this->attack = $atk; }
    function getAttack() { return $this->attack; }

And used like this:

echo $testcard->getAttack();

In these methods, I could check that the attack value that is getting set is an integer. Writing all these get/set methods can be a real pain. In Ruby, there are some special keywords to indicate this functionality.

class CharacterCard < Card 
  attr_reader :hasFlight, :hasRange, :attack, :defense
  attr_writer :hasFlight, :hasRange, :attack, :defense

The attr_reader, attr_writer specify a method for each to read/write.

So its used like:

testcard.attack = 5
echo testcard.attack

When I first saw this, I thought cool! .. but, then, I thought, what if you wanted to do data checking or something. Then you'd have to write your own methods anyways. But these might work in cases where you just want a plain jane get/set method. Maybe you don't need get/set for every variable. I suppose if you don't think you'll need it you shouldn't have it. Or should you? that’s the dilemma. I have sometimes. And, I like have getVAR setVAR. The ruby shortcuts don't allow that. I've seen people do php get/set functions like this:

function attack($val = "XX") {
	if ($val == "XX") {
		return $this->attack;
	} else {
		$this->attack = $val;

Used as:

echo $testcard->attack();

This can be used as both a get/set method. If a value is given (then the default value of XX is not sent in) then it sets the value, otherwise the current value is returned.

But I was thinking what if the value of XX (or null) is a valid value? then how do you know if a valid value is sent? And its kinda a pain to hammer out this code all the time (programmers are a lazy lot, aren't we?). So I wrote this little function to do the same thing:

    function setOrFetch($var, $args) {
        if (count($args) == 0) {
            return $this->{$var};
        } else {
            $this->{$var} = $args[0];
            return null;

Then its used like:

    function cardID() {
        $args = func_get_args();
        return $this->setOrFetch("cardID", $args);

I had initially put the line like this:

        return $this->setOrFetch("cardID", func_get_args());

PHP won't allow "func_get_args()" as a method parameter, so I had to place the value in a variable and pass the variable.

So what do you think? do you like have get / set in the method names of your get/set variables?

I could

But I may have private variables that I don't want anybody to get. If I name my get/set methods then I can control which values can go out.

I haven't even touched PHP5

Figured it would still be many years before I could use it at my job :)

Awesome, Thanks!

I haven't seen that, thanks :)