ชื่อเมธอดจากตัวแปรใน OOP ใน PHP

เช่นเดียวกับชื่อคุณสมบัติ (properties) ที่เก็บในตัวแปร เราก็สามารถเก็บชื่อเมธอดได้เช่นกัน มาดูตัวอย่างกัน สมมติว่าเรามีคลาส User นี้พร้อมกับ getters สำหรับคุณสมบัติต่างๆ:

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

มาสร้างออบเจ็กต์ของคลาสนี้:

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

สมมติว่าในตัวแปรเก็บ ชื่อเมธอด:

php<?php
  $method = 'getName';
?>

ลองเรียกเมธอด โดยใช้ชื่อจากตัวแปร:

php<?php
  echo $user->$method(); // จะแสดง 'john'
?>
Задание 1

กำหนดคลาสต่อไปนี้:

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

กำหนดอาร์เรย์:

php<?php
  $methods = [
    'method1' => 'getName',
    'method2' => 'getSalary',
    'method3' => 'getPosition',
  ];
?>

สร้างออบเจ็กต์ของคลาส Employee จากนั้นเข้าถึงคุณสมบัติของมัน ผ่านสมาชิกของอาร์เรย์