Metódusnév változóból az OOP-ban PHP-ben

A tulajdonságnevekhez hasonlóan a metódusneveket is tárolhatjuk változókban. Nézzük meg egy példán keresztül. Tegyük fel, hogy van egy User osztályunk getter tulajdonságokkal:

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

Hozzuk létre az osztály egy objektumát:

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

Tegyük fel, hogy egy változóban tároljuk a metódus nevét:

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

Hívjuk meg a metódust a változóból származó névvel:

php<?php
  echo $user->$method(); // kiírja 'john'-t
?>
Задание 1

Adott a következő osztály:

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

Adott egy tömb:

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

Hozz létre egy objektumot a Employee osztályból, majd a tulajdonságaihoz a tömb elemein keresztül férj hozzá.