views:

174

answers:

3

Just an idea:

example (in PHP): to set name: $object->name('name'); to get name: $object->name();

If no argument: the method is used as getter, else as setter. For simple getters/setter. Stupid, whatever, maybe?

edit: to follow up on the answers: I don't really like get and set because I prefer to have the interface as explicit as possible. When there are only a few properties it's also overkill IMHO. So I'd like to narrow it down to classes/objects with a couple of explicit getters/setters.

+2  A: 

The problem is it would be hard to follow. I'd much rather use PHP5's __get and __set so it is more natural to get and set variables, and everyone would know exactly what I am doing. IE:

class myClass
{

    function __get($name)
    {
       return $this->array[$name];
    }
    function __set($name, $value)
    {
       $this->array[$name] = $value;
    }
    function print()
    {
       echo $this->array['test'];
    }
}
$obj = new myClass;
$obj->test = "Hi";
echo $obj->test; //echos Hi.
$obj->print(); //echos Hi.
Chacha102
A: 

Sure, you could do that if it makes sense in your application, otherwise I would just use the standard getters/setters which have already been set up for you. Your function could look something like this:

public function name($val = null)
{
  if (is_null($val))
  {
    return $this->name;
  }
  else
  {
    $this->name = $val;
  }
}
James Skidmore
I'd like to know the reason behind the downvote.
koen
Me too... ;-)
James Skidmore
I wasn't the downvoter, but I'd like to point out that this kind of combined getter/setter doesn't allow you to set the property in question to NULL.
Otterfan
Good point Otterfan!
James Skidmore
+2  A: 

It can be done using the __call() magic method.

class Test {
    public function __call($name, array $args) {
        $variable =& $this->$name;
        if(!empty($args)) {
            $variable = $args[0];
        }
        return $variable;
    }
}
orlandu63
Are you intentionally returning the property for sets?
hobodave
Yes .
orlandu63
Its probably for brevity, but could be a nice side effect, especially if you put something in there to restrict what variables could be added.
Chacha102