2017-06-16 42 views
0

擴展構造方法:如何從我在我的用戶類創建的構造方法,父類

class User { 
    protected $name; 
    protected $title; 

    public function __construct($name = null, $title = null) { 
     $this->name = $name; 
     $this->title = $title; 
    } 
} 

現在,我想我的客戶端類內延伸構造方法。在用多個代碼塊「試驗」之後,我似乎無法弄清楚如何做到這一點。我希望$ company包含在初始化中。下面是最新版本的我不成功的代碼:

class Client extends User 
{ 
    protected $company; 

    public function __construct($company = null) 
    {  
    parent::__construct($name = null, $title = null); 
    $this->company = $company; 
    } 

    public function getCompany() 
    {   
    return $this->company; 
    } 

    public function setCompany($company) 
    {  
    $this->company = $company; 
    } 
} 

$MyPHPClassSkillLevel = newbie; 

我真的只是皮毛,所以任何的幫助深表感謝擴展類的表面。謝謝。

+1

它在做什麼或不做什麼?它看起來至少應該起作用,也許不是你想要的,但我們不知道。 – AbraCadaver

+0

'Client'構造函數應該可以接受'$ name'和'$ title'參數,所以它可以在構造父項時傳遞它們。 – Barmar

+0

噢,別忘了:爲了開發一個好的OOP解決方案,您需要對所謂的** S.O.L.I.D有一個很好的理解。原則**!還有更多(DRY,KISS等),但是SOLID是OOP的核心。 – 2017-06-16 16:48:02

回答

0

User班是完美的。 Client類幾乎是完美的:您只需將相同的構造函數參數($name$title)也傳遞給子類Client。並嘗試使用setter,如果你定義它們 - 如$this->setCompany($company)

class Client extends User 
{ 
    protected $company; 

    public function __construct($company = null, $name = null, $title = null) 
    {  
    parent::__construct($name, $title); 
    $this->setCompany($company); 
    } 

    public function getCompany() 
    {   
    return $this->company; 
    } 

    public function setCompany($company) 
    {  
    $this->company = $company; 
    } 
} 

當你定義的參數,你可以讓他們可選的 - 你已經在User那樣:

public function __construct($name = null, $title = null) { 
    //... 
} 

但是,當你傳遞參數,例如爲所定義的參數賦值,則無效將其作爲「可選」傳遞。所以,在Client類,這是無效的:

parent::__construct($name = null, $title = null); 

但這是:

parent::__construct($name, $title); 

我也建議你:The Clean Code Talks - Don't Look For Things!(只是要確定)。

+0

我很高興我能幫上忙。祝你好運! – 2017-06-16 16:42:36

+0

謝謝@aendeerei! – jpradcliffe

+0

@jpradcliffe不客氣。我只是給你的原始問題寫了一篇小而重要的評論。隨意問更多,好嗎?再見 – 2017-06-16 16:49:39

相關問題