简体   繁体   中英

How to Extend Construct Method from Parent Class

I have created a construct method in my User Class:

class User {
    protected $name;
    protected $title;

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

Now I want to extend the construct method within my Client Class. After "experimenting" with multiple code blocks I don't seem to be able to get my head around how to do this. I want $company to be included with initialization. Here is the latest version of my unsuccessful code:

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;

I'm really just scratching the surface of extending classes so any help is much appreciated. Thank you.

The User class is perfect. The Client class is almost perfect: you just need to pass the same constructor arguments ( $name and $title ) to the subclass Client too. And try to also use the setters, if you define them - like $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;
  }
}

When you DEFINE parameters, you can make them optional - what you already did in User :

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

But, when you PASS arguments, eg valulues for the defined parameters, then is not valid to pass them as "optional". So, in class Client , this is not valid:

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

But this it is:

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

I would also recommend you this: The Clean Code Talks - Don't Look For Things! (just to be sure).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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