简体   繁体   English

获取器和设置器的代码布局

[英]Code Layout for getters and setters

I am writing a class that has lots of getters and setters and was wondering on what people thought about the following: 我正在编写一个包含许多吸气剂和吸气剂的课程,并且想知道人们对以下内容的看法:

The normal way is to code like the following: 正常的方式是如下代码:

public function setChangeSort($changeSort)
{
    self::$changeSort = $changeSort;
}

public function getChangeSort()
{
    return self::$changeSort;
}

What are your opinions on doing the following: 您对执行以下操作有何看法:

public function setChangeSort($changeSort) { self::$changeSort = $changeSort; }
public function getChangeSort() { return self::$changeSort; }

I have no problem doing it the orginal way, as that is how it shoul be done. 我完全可以按原样进行操作,因为这应该做到。 It just seems to take up alot of space in my classon functions that are really obvious in what they do. 它似乎在我的classon函数中占据了很多空间,这些空间在它们的工作中确实很明显。

Thanks in advance. 提前致谢。

如果它们是一致的,显而易见的和直观的,则单行条件块就可以了,尽管我鼓励小心地将它们隔开,所以很明显它们是函数而不是某些单行代码!

I would go with the "one-line" variation. 我会选择“单行”变体。 But only if all it does is setting and getting a value. 但是, 只有要做的就是设定并获得价值。 if you add a check for null or any other validation, or doing anything other than getting or setting I would go with the first and longer variation to keep the code more readable. 如果您添加了一个用于null或其他任何验证的检查,或者执行除获取或设置以外的任何其他操作,则我会采用第一个也是更长的版本,以使代码更具可读性。

I usually threat one-line methods in the same way as the other methods. 我通常以与其他方法相同的方式威胁单行方法。 I don't mind my source code to be N-lines longer if it means it is more readable and maintainable. 我不介意我的源代码更长一些,因为这意味着它更具可读性和可维护性。

I would also suggesto to checkout the following document http://framework.zend.com/manual/en/coding-standard.html IMHO it's the best PHP coding standard reference available so far. 我也建议您查看以下文档http://framework.zend.com/manual/zh-CN/coding-standard.html恕我直言,这是迄今为止最好的PHP编码标准参考。

I think magic getters/setters of PHP5 are really helpful when dealing with numerous getters/setters. 我认为PHP5的神奇的getter / setter在处理大量的getter / setter时确实很有帮助。

http://fr.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members http://fr.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

And an example. 还有一个例子。

<?php
class A {
  private $properties = array();

  public function __set($key, $value) {
    if (is_array($value)) {
      $this->$key = $value;
    } else {
      $this->properties[$key] = $value;
    }
  }

  public function __get($key) {
    if (array_key_exists($key, $this->properties)) {
      return $this->properties[$key];
    }

    return null;
  }
}
?> 

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

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