如何从父类扩展构造方法

时间:2017-06-16 16:22:56

标签: php oop

我在我的用户类中创建了一个构造方法:

class User {
    protected $name;
    protected $title;

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

现在我想在我的Client Class中扩展构造方法。在使用多个代码块进行“试验”之后,我似乎无法理解如何执行此操作。我希望$ 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 个答案:

答案 0 :(得分: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;
  }
}

当你DEFINE参数时,你可以将它们作为可选项 - 你在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!(只是为了确定)。