Ime metode iz spremenljivke v OOP v PHP

Po analogiji z imeni lastnosti v spremenljivki lahko shranimo tudi imena metod. Poglejmo si na primeru. Naj imamo dan tak razred User z getterji lastnosti:

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

Ustvarimo objekt tega razreda:

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

Naj v spremenljivki hrani ime metode:

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

Pokličimo metodo z imenom iz spremenljivke:

php<?php
  echo $user->$method(); // izpiše 'john'
?>
Задание 1

Dan je naslednji razred:

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

Dan je seznam:

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

Ustvarite objekt razreda Employee, nato pa dostopite do njegovih lastnosti prek elementov seznama.