PHP တွင် OOP အမွေဆက်ခံခြင်းအတွက် Constructor

အမွေဆက်ခံသည့်အခါ မိဘ class ၏ constructor ကို override လုပ်နိုင်ပါသည်။ ဥပမာတစ်ခုဖြင့် ကြည့်ရအောင်။ အောက်ပါအတိုင်း မိဘ class ရှိသည်ဆိုပါစို့။

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;
    }
  }
?>

မိဘ class မှ အောက်ပါ class က အမွေဆက်ခံသည်ဆိုပါစို့။

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

အမွေဆက်ခံသော class တွင် constructor ကို ထပ်တိုး parameter များထည့်၍ ချဲ့ထွင်လိုသည်ဆိုပါစို့။

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

ဤသို့ဖြစ်လျှင် parent::__construct() ကို အသုံးပြု၍ ပထမဆုံးစာကြောင်းတွင် မိဘ၏ constructor ကို ခေါ်ရန် လိုအပ်ပါသည်။

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

အမှန်တော့ parent::__construct() command သည် မိဘ၏ constructor ပင်ဖြစ်သည်။ ထို့ကြောင့် လိုအပ်သော parameter များကို ထည့်ပေးပါ။

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

ယခု အမွေဆက်ခံသော class တွင် သင်ကြားမည့်နှစ်ကို ၎င်း၏ကိုယ်ပိုင် property တွင်ရေးပါ။

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

သင်ကြားမည့်နှစ်အတွက် getter method ပြုလုပ်ပါ။

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

Employee class သည် ဤသင်ခန်းစာမှ User class မှ အမွေဆက်ခံသည်ဆိုပါစို့။

Задание 2

Employee class ထဲတွင် မိဘ class ၏ constructor ကို အသက်နှင့် လစာဆိုင်သော parameter များထည့်၍ override ပြုလုပ်ပါ။

Задание 3

အသက်နှင့် လစာအတွက် getter method များ ပြုလုပ်ပါ။