Օբյեկտի մեթոդի անունը փոփոխականից OOP-ում PHP-ում

Հատկությունների անունները փոփոխականում պահելու նման կարելի է պահել նաև մեթոդների անունները: Եկեք նայենք օրինակի վրա: Ենթադրենք, մենք ունենք User դասը հատկությունների գետթերներով.

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 դասի օբյեկտ, ապա դիմեք նրա հատկություններին զանգվածի տարրերի միջոցով: