dongnaizao8039 2017-05-30 16:34
浏览 43
已采纳

私有属性访问与构造函数的setter与构造函数的直接访问

In TrainBoardingCard we have setTrainCode is it ok to use $this->trainCode = $trainCode inside constructor or we shoud always use setTrainCode like $this->setTrainCode($trainCode); as it could have some logic in future.

For both case what are the pros and cons? please let us know your preference with reasons.

class TrainBoardingCard extends BoardingCard
{
    /**
     * @var string
     */
    private $trainCode;

    /**
     * @param string $trainCode
     */
    public function __construct(string $trainCode)
    {
        $this->trainCode = $trainCode;
    }

    /**
     * @return string
     */
    public function getTrainCode(): string
    {
        return $this->trainCode;
    }

    /**
     * @param string $trainCode
     */
    public function setTrainCode(string $trainCode)
    {
        $this->trainCode = $trainCode;
    }
}
  • 写回答

1条回答 默认 最新

  • douzhang1926 2017-05-30 17:55
    关注

    It depends.

    You could say there are two different schools of thought and they both deal with both setters and constructors.

    1. The object must be created already valid state. This state can be changed with atomic operation from one valid state to another. This means, that you class doesn't actually have simple setters per se.

      $client = new Client(
          new FullName($name, $surname),
          new Country($country);
          new Address($city, street, $number));
      
      // do something
      
      $client->changeLocation(
          new Country('UK'),
          new Address('London', 'Downing St.', '10'));
      
    2. Constructor is used only do pass in dependencies and not to impart state. The object's state by default is blank and it gets changed only by using setters externally.

      $client new Client();
      $client->setId(14);
      
      $mapper = new DataMapper(new PDO('...'), $config);        
      $mapper->fetch($client);
      
      if ($client->getCity() === 'Berlin') {
          $client->setCity('London');
          $mapper->store($client);
      }
      

    Or you can have a mix or both, but that would cause some confusion.

    Not sure if this will make it better for you or worse :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?