简体   繁体   English

一种方法中的设置器/获取器

[英]setters/getters in one method

Just an idea: 只是一个想法:

example (in PHP): to set name: $object->name('name'); 示例(在PHP中):设置名称:$ object-> name('name'); to get name: $object->name(); 获得名称:$ object-> name();

If no argument: the method is used as getter, else as setter. 如果没有参数:该方法用作getter,否则用作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. 编辑:跟进答案:我真的不喜欢get和set,因为我更喜欢使接口尽可能明确。 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. 因此,我想通过几个显式的getter / setter将其范围缩小到类/对象。

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. 我宁愿使用PHP5的__get和__set,所以获取和设置变量更加自然,每个人都确切地知道我在做什么。 IE: 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. 可以使用__call()魔术方法来完成。

class Test {
    public function __call($name, array $args) {
        $variable =& $this->$name;
        if(!empty($args)) {
            $variable = $args[0];
        }
        return $variable;
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM