PHP တွင် OOP အမွေဆက်ခံခြင်းအတွင်း Private Properties ၏ပြဿနာ

Private properties များသည်အမွေဆက်ခံခြင်းမရှိသည့်အချက်သည် မျှော်လင့်မထားသောပြဿနာတစ်ခုကိုဖြစ်ပေါ်စေနိုင်သည်။ ဥပမာတစ်ခုအားဖြင့်ကြည့်ရှုကြပါစို့။ ကျွန်ုပ်တို့တွင် private property တစ်ခုပါသော မိဘ class တစ်ခုရှိသည်ဆိုပါစို့။

php<?php
  class User {
    private $age;
    
    public function setAge($age) {
      $this->age = $age;
    }
    public function getAge() {
      return $this->age;
    }
  }
?>

ခုလက်ရှိ ဆက်ခံထားသော class တွင် အသက်တစ်နှစ်တိုးပေးမည့်မူဝါဒတစ်ခုလုပ်ဆောင်ရန် ဆုံးဖြတ်ထားသည်ဆိုပါစို့။ သို့သော် မိဘ၏ private property ကိုပြောင်းလဲရန် ကြိုးပမ်းမှုသည် မှားယွင်းမှုတစ်ခုကိုဖြစ်ပေါ်စေမည်။

php<?php
  class Student extends User {
    public function incAge() {
      $this->age++; // မှားယွင်းမှု
    }
  }
?>

ဆက်ခံထားသော class တွင် private property $age ကိုကြေညာပါက မှားယွင်းမှုပျောက်ကွယ်သွားမည်။

php<?php
  class Student extends User {
    private $age;
    
    public function incAge() {
      $this->age++;
    }
  }
?>

ဤနေရာတွင်ကျွန်ုပ်တို့ကိုထောင်ချောက်ဆင်ထားသည်။ အမှန်တကယ်တွင် private properties နှစ်ခုကိုကျွန်ုပ်တို့ဖန်တီးမိသည်။ တစ်ခုမှာမိဘတွင်ဖြစ်ပြီး၊ နောက်တစ်ခုမှာဆက်ခံသူတွင်ဖြစ်သည်။ ထို့အပြင် ၎င်းတို့သည်လုံးဝသီးခြားစီအလုပ်လုပ်သည်။ ဆိုလိုသည်မှာ မိဘ၏ methods များသည် ၎င်း၏ property ကိုပြောင်းလဲမည်ဖြစ်ပြီး ဆက်ခံသူ၏ methods များသည် ၎င်းတို့၏ property ကိုပြောင်းလဲမည်ဖြစ်သည်။

ဤပြဿနာတွင်အမှန်တကယ်ဖြေရှင်းနည်းရှိသည်။ မိဘ၏ private properties များကို ၎င်းမိဘ၏ methods များမှတဆင့် ကိုင်တွယ်ခြင်းဖြင့်သာဖြစ်သည်။ ကျွန်ုပ်တို့၏ကုဒ်ကိုဤအချက်နှင့်ကိုက်ညီစွာ ပြန်လည်ရေးသားကြပါစို့။

php<?php
  class Student extends User {
    public function incAge() {
      $age = $this->getAge();
      $age++;
      $this->setAge($age);
    }
  }
?>

ရိုးရှင်းအောင်ပြုလုပ်နိုင်သည်။

php<?php
  class Student extends User {
    public function incAge() {
      $this->setAge($this->getAge() + 1);
    }
  }
?>
Задание 1

အောက်ပါကုဒ်တွင် ဆက်ခံထားသော class ၌ မိဘ၏ method ကိုအစားထိုးထားသည်။ ဤကုဒ်ရှိပြဿနာများကိုပြင်ဆင်ပေးပါ။

php<?php
  class User {
    private $name;
    
    public function setName($name) {
      $this->name = $name;
    }
    public function getName() {
      return $this->name;
    }
  }
  
  class Employee extends User {
    public function setName($name) {
      if (strlen($name) > 0) {
        $this->name = $name; // မှားယွင်းမှု
      }
    }
  }
?>