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 :)

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

报告相同问题?