PHP OOP တွင် function မှ property အမည်ကို ရယူခြင်း

Object ၏ property အမည်ကိုလည်း function မှ ရယူနိုင်ပါသည်။ ဤသို့မည်သို့လုပ်ဆောင်ရမည်ကို ကြည့်ရအောင်။ ကျွန်ုပ်တို့တွင် အောက်ပါ User class ရှိသည်ဟု ဆိုကြပါစို့။

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

ဤ class ၏ object တစ်ခုကို ဖန်တီးကြပါစို့။

php<?php
  $user = new User('john', 'smit');
?>

ကျွန်ုပ်တို့တွင် အောက်ပါ function ရှိသည်ဟု ဆိုကြပါစို့။

php<?php
  function getProp()
  {
    return 'name';
  }
?>

Object ၏ property ကို ကျွန်ုပ်တို့၏ function မှ ပြန်ပေးသည့် အမည်ဖြင့် ရယူကြည့်ပါမည်။

php<?php
  echo $user->{getProp()}; // 'john' ကို ပြသမည်
?>
Задание 1

အောက်ပါ class ကို ပေးထားပါသည်။

php<?php
  class Employee
  {
    public $name;
    public $salary;
    public $position;
    
    public function __construct($name, $salary, $position)
    {
      $this->name = $name;
      $this->salary = $salary;
      $this->position = $position;
    }
  }
?>

အောက်ပါ function များကို ပေးထားပါသည်။

php<?php
  function getProp1()
  {
    return 'name';
  }
  function getProp2()
  {
    return 'salary';
  }
?>

Employee class ၏ object တစ်ခုကို ဖန်တီးပါ၊ ထို့နောက် ၎င်း၏ properties များကို function များ run ပြီးရရှိလာသော ရလဒ်များမှတစ်ဆင့် ရယူပါ။