Constructor khi kế thừa trong OOP PHP

Khi kế thừa, bạn có thể ghi đè constructor của lớp cha. Hãy xem ví dụ. Giả sử chúng ta có lớp cha sau:

php<?php
  class User {
    private $name;
    private $surn;
    
    public function __construct($name, $surn) {
      $this->name = $name;
      $this->surn = $surn;
    }
    
    public function getName() {
      return $this->name;
    }
    public function getSurn() {
      return $this->surn;
    }
  }
?>

Giả sử lớp sau kế thừa từ lớp cha:

php<?php
  class Student extends User {
    
  }
?>

Giả sử chúng ta muốn mở rộng constructor trong lớp con, thêm vào nó các tham số bổ sung:

php<?php
  class Student extends User {
    private $year;
    
    public function __construct($name, $surn, $year) {
      
    }
  }
?>

Trong trường hợp này, chúng ta bắt buộc phải gọi constructor của lớp cha trong dòng đầu tiên thông qua parent::__construct():

php<?php
  class Student extends User {
    private $year;
    
    public function __construct($name, $surn, $year) {
      parent::__construct($name, $surn);
    }
  }
?>

Lệnh parent::__construct() về bản chất là constructor của lớp cha. Vì vậy hãy truyền các tham số cần thiết vào nó:

php<?php
  class Student extends User {
    private $year;
    
    public function __construct($name, $surn, $year) {
      parent::__construct($name, $surn);
    }
  }
?>

Bây giờ trong lớp con, hãy ghi năm học vào thuộc tính riêng của lớp con:

php<?php
  class Student extends User {
    private $year;
    
    public function __construct($name, $surn, $year) {
      parent::__construct($name, $surn);
      $this->year = $year;
    }
  }
?>

Hãy tạo getter cho năm học:

php<?php
  class Student extends User {
    private $year;
    
    public function __construct($name, $surn, $year) {
      parent::__construct($name, $surn);
      $this->year = $year;
    }
    
    public function getYear() {
      return $this->year;
    }
  }
?>
Задание 1

Giả sử lớp Employee kế thừa từ lớp User trong bài học này.

Задание 2

Hãy ghi đè trong lớp Employee constructor của lớp cha, thêm vào nó tham số về tuổi và lương.

Задание 3

Hãy tạo getter cho tuổi và lương.