2017-05-30 85 views
0

在TrainBoardingCard我們setTrainCode可以使用$ this-> trainCode = $ trainCode在構造函數中,或者我們總是使用setTrainCode像$ this-> setTrainCode($ trainCode );因爲它將來可能有一些邏輯。私人財產訪問與構造函數的setter與構造函數的直接訪問

對於這兩種情況有什麼優點和缺點?請讓我們知道你的偏好和理由。

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

這取決於。

你可以說有兩個不同的思想流派他們都處理建立者和構造者。

  1. 該對象必須被創建爲有效狀態。這種狀態可以通過原子操作從一個有效狀態改變到另一個有效狀態。這意味着,你的課程實際上並沒有簡單的設置者 / 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. 構造函數只用於傳遞依賴關係而不傳遞狀態。該對象的狀態默認爲空白,僅在外部使用setter纔會更改。

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

或者你可以有一個組合或兩者兼而有之,但這樣會造成一些混亂。

不知道這將使它更好地爲您或更糟:)

+0

感謝teresko你有用的信息, –

+0

有一點仍不清楚我的,裏面的構造,我們可以做到這一點$這個 - > trainCode = $ trainCode;或者應該總是做$ this-> setTrainCode($ trainCode);如果我們有二傳手(可能二傳手可以有一些邏輯在未來可能不會)。 –

+0

如果你在構造函數中傳遞的是依賴項(如在其他對象中),那麼這不是必需的。如果你傳遞值(或值對象),那麼使用setter將是一個好主意。 –