Question

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.

Was it helpful?

Solution

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;
  }
}

OTHER TIPS

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.

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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top